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., 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"
32 #include <sys/types.h>
39 #include <selinux/selinux.h>
40 #include <selinux/avc.h>
41 #include <selinux/av_permissions.h>
42 #include <selinux/flask.h>
48 #endif /* HAVE_LIBAUDIT */
49 #endif /* HAVE_SELINUX */
51 #define BUS_SID_FROM_SELINUX(sid) ((BusSELinuxID*) (sid))
52 #define SELINUX_SID_FROM_BUS(sid) ((security_id_t) (sid))
55 /* Store the value telling us if SELinux is enabled in the kernel. */
56 static dbus_bool_t selinux_enabled = FALSE;
58 /* Store an avc_entry_ref to speed AVC decisions. */
59 static struct avc_entry_ref aeref;
61 /* Store the SID of the bus itself to use as the default. */
62 static security_id_t bus_sid = SECSID_WILD;
64 /* Thread to listen for SELinux status changes via netlink. */
65 static pthread_t avc_notify_thread;
67 /* Prototypes for AVC callback functions. */
68 static void log_callback (const char *fmt, ...);
69 static void log_audit_callback (void *data, security_class_t class, char *buf, size_t bufleft);
70 static void *avc_create_thread (void (*run) (void));
71 static void avc_stop_thread (void *thread);
72 static void *avc_alloc_lock (void);
73 static void avc_get_lock (void *lock);
74 static void avc_release_lock (void *lock);
75 static void avc_free_lock (void *lock);
77 /* AVC callback structures for use in avc_init. */
78 static const struct avc_memory_callback mem_cb =
80 .func_malloc = dbus_malloc,
81 .func_free = dbus_free
83 static const struct avc_log_callback log_cb =
85 .func_log = log_callback,
86 .func_audit = log_audit_callback
88 static const struct avc_thread_callback thread_cb =
90 .func_create_thread = avc_create_thread,
91 .func_stop_thread = avc_stop_thread
93 static const struct avc_lock_callback lock_cb =
95 .func_alloc_lock = avc_alloc_lock,
96 .func_get_lock = avc_get_lock,
97 .func_release_lock = avc_release_lock,
98 .func_free_lock = avc_free_lock
100 #endif /* HAVE_SELINUX */
103 * Log callback to log denial messages from the AVC.
104 * This is used in avc_init. Logs to both standard
107 * @param fmt the format string
108 * @param variable argument list
113 static int audit_fd = -1;
117 bus_selinux_audit_init(void)
120 audit_fd = audit_open ();
124 /* If kernel doesn't support audit, bail out */
125 if (errno == EINVAL || errno == EPROTONOSUPPORT || errno == EAFNOSUPPORT)
127 /* If user bus, bail out */
128 if (errno == EPERM && getuid() != 0)
130 _dbus_warn ("Failed opening connection to the audit subsystem");
132 #endif /* HAVE_LIBAUDIT */
136 log_callback (const char *fmt, ...)
145 char buf[PATH_MAX*2];
147 /* FIXME: need to change this to show real user */
148 vsnprintf(buf, sizeof(buf), fmt, ap);
149 audit_log_user_avc_message(audit_fd, AUDIT_USER_AVC, buf, NULL, NULL,
153 #endif /* HAVE_LIBAUDIT */
155 vsyslog (LOG_INFO, fmt, ap);
160 * On a policy reload we need to reparse the SELinux configuration file, since
161 * this could have changed. Send a SIGHUP to reload all configs.
164 policy_reload_callback (u_int32_t event, security_id_t ssid,
165 security_id_t tsid, security_class_t tclass,
166 access_vector_t perms, access_vector_t *out_retained)
168 if (event == AVC_CALLBACK_RESET)
169 return raise (SIGHUP);
175 * Log any auxiliary data
178 log_audit_callback (void *data, security_class_t class, char *buf, size_t bufleft)
180 DBusString *audmsg = data;
182 if (bufleft > (size_t) _dbus_string_get_length(audmsg))
184 _dbus_string_copy_to_buffer_with_nul (audmsg, buf, bufleft);
190 _dbus_string_init_const(&s, "Buffer too small for audit message");
192 if (bufleft > (size_t) _dbus_string_get_length(&s))
193 _dbus_string_copy_to_buffer_with_nul (&s, buf, bufleft);
198 * Create thread to notify the AVC of enforcing and policy reload
199 * changes via netlink.
201 * @param run the thread run function
202 * @return pointer to the thread
205 avc_create_thread (void (*run) (void))
209 rc = pthread_create (&avc_notify_thread, NULL, (void *(*) (void *)) run, NULL);
212 _dbus_warn ("Failed to start AVC thread: %s\n", _dbus_strerror (rc));
215 return &avc_notify_thread;
218 /* Stop AVC netlink thread. */
220 avc_stop_thread (void *thread)
222 pthread_cancel (*(pthread_t *) thread);
225 /* Allocate a new AVC lock. */
227 avc_alloc_lock (void)
229 pthread_mutex_t *avc_mutex;
231 avc_mutex = dbus_new (pthread_mutex_t, 1);
232 if (avc_mutex == NULL)
234 _dbus_warn ("Could not create mutex: %s\n", _dbus_strerror (errno));
237 pthread_mutex_init (avc_mutex, NULL);
242 /* Acquire an AVC lock. */
244 avc_get_lock (void *lock)
246 pthread_mutex_lock (lock);
249 /* Release an AVC lock. */
251 avc_release_lock (void *lock)
253 pthread_mutex_unlock (lock);
256 /* Free an AVC lock. */
258 avc_free_lock (void *lock)
260 pthread_mutex_destroy (lock);
263 #endif /* HAVE_SELINUX */
266 * Return whether or not SELinux is enabled; must be
267 * called after bus_selinux_init.
270 bus_selinux_enabled (void)
273 return selinux_enabled;
276 #endif /* HAVE_SELINUX */
280 * Do early initialization; determine whether SELinux is enabled.
283 bus_selinux_pre_init (void)
287 _dbus_assert (bus_sid == SECSID_WILD);
289 /* Determine if we are running an SELinux kernel. */
290 r = is_selinux_enabled ();
293 _dbus_warn ("Could not tell if SELinux is enabled: %s\n",
294 _dbus_strerror (errno));
298 selinux_enabled = r != 0;
306 * Initialize the user space access vector cache (AVC) for D-Bus and set up
310 bus_selinux_full_init (void)
315 _dbus_assert (bus_sid == SECSID_WILD);
317 if (!selinux_enabled)
319 _dbus_verbose ("SELinux not enabled in this kernel.\n");
323 _dbus_verbose ("SELinux is enabled in this kernel.\n");
325 avc_entry_ref_init (&aeref);
326 if (avc_init ("avc", &mem_cb, &log_cb, &thread_cb, &lock_cb) < 0)
328 _dbus_warn ("Failed to start Access Vector Cache (AVC).\n");
333 openlog ("dbus", LOG_PERROR, LOG_USER);
334 _dbus_verbose ("Access Vector Cache (AVC) started.\n");
337 if (avc_add_callback (policy_reload_callback, AVC_CALLBACK_RESET,
338 NULL, NULL, 0, 0) < 0)
340 _dbus_warn ("Failed to add policy reload callback: %s\n",
341 _dbus_strerror (errno));
347 bus_sid = SECSID_WILD;
349 if (getcon (&bus_context) < 0)
351 _dbus_verbose ("Error getting context of bus: %s\n",
352 _dbus_strerror (errno));
356 if (avc_context_to_sid (bus_context, &bus_sid) < 0)
358 _dbus_verbose ("Error getting SID from bus context: %s\n",
359 _dbus_strerror (errno));
360 freecon (bus_context);
364 freecon (bus_context);
366 #endif /* HAVE_SELINUX */
371 * Decrement SID reference count.
373 * @param sid the SID to decrement
376 bus_selinux_id_unref (BusSELinuxID *sid)
379 if (!selinux_enabled)
382 _dbus_assert (sid != NULL);
384 sidput (SELINUX_SID_FROM_BUS (sid));
385 #endif /* HAVE_SELINUX */
389 bus_selinux_id_ref (BusSELinuxID *sid)
392 if (!selinux_enabled)
395 _dbus_assert (sid != NULL);
397 sidget (SELINUX_SID_FROM_BUS (sid));
398 #endif /* HAVE_SELINUX */
402 * Determine if the SELinux security policy allows the given sender
403 * security context to go to the given recipient security context.
404 * This function determines if the requested permissions are to be
405 * granted from the connection to the message bus or to another
406 * optionally supplied security identifier (e.g. for a service
407 * context). Currently these permissions are either send_msg or
408 * acquire_svc in the dbus class.
410 * @param sender_sid source security context
411 * @param override_sid is the target security context. If SECSID_WILD this will
412 * use the context of the bus itself (e.g. the default).
413 * @param target_class is the target security class.
414 * @param requested is the requested permissions.
415 * @returns #TRUE if security policy allows the send.
419 bus_selinux_check (BusSELinuxID *sender_sid,
420 BusSELinuxID *override_sid,
421 security_class_t target_class,
422 access_vector_t requested,
425 if (!selinux_enabled)
428 /* Make the security check. AVC checks enforcing mode here as well. */
429 if (avc_has_perm (SELINUX_SID_FROM_BUS (sender_sid),
431 SELINUX_SID_FROM_BUS (override_sid) :
432 SELINUX_SID_FROM_BUS (bus_sid),
433 target_class, requested, &aeref, auxdata) < 0)
435 _dbus_verbose ("SELinux denying due to security policy.\n");
441 #endif /* HAVE_SELINUX */
444 * Returns true if the given connection can acquire a service,
445 * assuming the given security ID is needed for that service.
447 * @param connection connection that wants to own the service
448 * @param service_sid the SID of the service from the table
449 * @returns #TRUE if acquire is permitted.
452 bus_selinux_allows_acquire_service (DBusConnection *connection,
453 BusSELinuxID *service_sid,
454 const char *service_name,
458 BusSELinuxID *connection_sid;
463 if (!selinux_enabled)
466 connection_sid = bus_connection_get_selinux_id (connection);
467 if (!dbus_connection_get_unix_process_id (connection, &spid))
470 if (!_dbus_string_init (&auxdata))
473 if (!_dbus_string_append (&auxdata, "service="))
476 if (!_dbus_string_append (&auxdata, service_name))
481 if (!_dbus_string_append (&auxdata, " spid="))
484 if (!_dbus_string_append_uint (&auxdata, spid))
488 ret = bus_selinux_check (connection_sid,
494 _dbus_string_free (&auxdata);
498 _dbus_string_free (&auxdata);
504 #endif /* HAVE_SELINUX */
508 * Check if SELinux security controls allow the message to be sent to a
509 * particular connection based on the security context of the sender and
510 * that of the receiver. The destination connection need not be the
511 * addressed recipient, it could be an "eavesdropper"
513 * @param sender the sender of the message.
514 * @param proposed_recipient the connection the message is to be sent to.
515 * @returns whether to allow the send
518 bus_selinux_allows_send (DBusConnection *sender,
519 DBusConnection *proposed_recipient,
521 const char *interface,
523 const char *error_name,
524 const char *destination,
528 BusSELinuxID *recipient_sid;
529 BusSELinuxID *sender_sid;
530 unsigned long spid, tpid;
533 dbus_bool_t string_alloced;
535 if (!selinux_enabled)
538 if (!sender || !dbus_connection_get_unix_process_id (sender, &spid))
540 if (!proposed_recipient || !dbus_connection_get_unix_process_id (proposed_recipient, &tpid))
543 string_alloced = FALSE;
544 if (!_dbus_string_init (&auxdata))
546 string_alloced = TRUE;
548 if (!_dbus_string_append (&auxdata, "msgtype="))
551 if (!_dbus_string_append (&auxdata, msgtype))
556 if (!_dbus_string_append (&auxdata, " interface="))
558 if (!_dbus_string_append (&auxdata, interface))
564 if (!_dbus_string_append (&auxdata, " member="))
566 if (!_dbus_string_append (&auxdata, member))
572 if (!_dbus_string_append (&auxdata, " error_name="))
574 if (!_dbus_string_append (&auxdata, error_name))
580 if (!_dbus_string_append (&auxdata, " dest="))
582 if (!_dbus_string_append (&auxdata, destination))
588 if (!_dbus_string_append (&auxdata, " spid="))
591 if (!_dbus_string_append_uint (&auxdata, spid))
597 if (!_dbus_string_append (&auxdata, " tpid="))
600 if (!_dbus_string_append_uint (&auxdata, tpid))
604 sender_sid = bus_connection_get_selinux_id (sender);
605 /* A NULL proposed_recipient means the bus itself. */
606 if (proposed_recipient)
607 recipient_sid = bus_connection_get_selinux_id (proposed_recipient);
609 recipient_sid = BUS_SID_FROM_SELINUX (bus_sid);
611 ret = bus_selinux_check (sender_sid,
617 _dbus_string_free (&auxdata);
623 _dbus_string_free (&auxdata);
629 #endif /* HAVE_SELINUX */
633 bus_selinux_append_context (DBusMessage *message,
640 if (avc_sid_to_context (SELINUX_SID_FROM_BUS (sid), &context) < 0)
645 dbus_set_error (error, DBUS_ERROR_FAILED,
646 "Error getting context from SID: %s\n",
647 _dbus_strerror (errno));
650 if (!dbus_message_append_args (message,
657 _DBUS_SET_OOM (error);
668 * Gets the security context of a connection to the bus. It is up to
669 * the caller to freecon() when they are done.
671 * @param connection the connection to get the context of.
672 * @param con the location to store the security context.
673 * @returns #TRUE if context is successfully obtained.
677 bus_connection_read_selinux_context (DBusConnection *connection,
682 if (!selinux_enabled)
685 _dbus_assert (connection != NULL);
687 if (!dbus_connection_get_unix_fd (connection, &fd))
689 _dbus_verbose ("Failed to get file descriptor of socket.\n");
693 if (getpeercon (fd, con) < 0)
695 _dbus_verbose ("Error getting context of socket peer: %s\n",
696 _dbus_strerror (errno));
700 _dbus_verbose ("Successfully read connection context.\n");
703 #endif /* HAVE_SELINUX */
706 * Read the SELinux ID from the connection.
708 * @param connection the connection to read from
709 * @returns the SID if successfully determined, #NULL otherwise.
712 bus_selinux_init_connection_id (DBusConnection *connection,
719 if (!selinux_enabled)
722 if (!bus_connection_read_selinux_context (connection, &con))
724 dbus_set_error (error, DBUS_ERROR_FAILED,
725 "Failed to read an SELinux context from connection");
726 _dbus_verbose ("Error getting peer context.\n");
730 _dbus_verbose ("Converting context to SID to store on connection\n");
732 if (avc_context_to_sid (con, &sid) < 0)
737 dbus_set_error (error, DBUS_ERROR_FAILED,
738 "Error getting SID from context \"%s\": %s\n",
739 con, _dbus_strerror (errno));
741 _dbus_warn ("Error getting SID from context \"%s\": %s\n",
742 con, _dbus_strerror (errno));
749 return BUS_SID_FROM_SELINUX (sid);
752 #endif /* HAVE_SELINUX */
757 * Function for freeing hash table data. These SIDs
758 * should no longer be referenced.
761 bus_selinux_id_table_free_value (BusSELinuxID *sid)
764 /* NULL sometimes due to how DBusHashTable works */
766 bus_selinux_id_unref (sid);
767 #endif /* HAVE_SELINUX */
771 * Creates a new table mapping service names to security ID.
772 * A security ID is a "compiled" security context, a security
773 * context is just a string.
775 * @returns the new table or #NULL if no memory
778 bus_selinux_id_table_new (void)
780 return _dbus_hash_table_new (DBUS_HASH_STRING,
781 (DBusFreeFunction) dbus_free,
782 (DBusFreeFunction) bus_selinux_id_table_free_value);
786 * Hashes a service name and service context into the service SID
787 * table as a string and a SID.
789 * @param service_name is the name of the service.
790 * @param service_context is the context of the service.
791 * @param service_table is the table to hash them into.
792 * @return #FALSE if not enough memory
795 bus_selinux_id_table_insert (DBusHashTable *service_table,
796 const char *service_name,
797 const char *service_context)
804 if (!selinux_enabled)
810 key = _dbus_strdup (service_name);
814 if (avc_context_to_sid ((char *) service_context, &sid) < 0)
822 _dbus_warn ("Error getting SID from context \"%s\": %s\n",
823 (char *) service_context,
824 _dbus_strerror (errno));
828 if (!_dbus_hash_table_insert_string (service_table,
830 BUS_SID_FROM_SELINUX (sid)))
833 _dbus_verbose ("Parsed \tservice: %s \n\t\tcontext: %s\n",
837 /* These are owned by the hash, so clear them to avoid unref */
844 if (sid != SECSID_WILD)
853 #endif /* HAVE_SELINUX */
858 * Find the security identifier associated with a particular service
859 * name. Return a pointer to this SID, or #NULL/SECSID_WILD if the
860 * service is not found in the hash table. This should be nearly a
861 * constant time operation. If SELinux support is not available,
862 * always return NULL.
864 * @param service_table the hash table to check for service name.
865 * @param service_name the name of the service to look for.
866 * @returns the SELinux ID associated with the service
869 bus_selinux_id_table_lookup (DBusHashTable *service_table,
870 const DBusString *service_name)
875 sid = SECSID_WILD; /* default context */
877 if (!selinux_enabled)
880 _dbus_verbose ("Looking up service SID for %s\n",
881 _dbus_string_get_const_data (service_name));
883 sid = _dbus_hash_table_lookup_string (service_table,
884 _dbus_string_get_const_data (service_name));
886 if (sid == SECSID_WILD)
887 _dbus_verbose ("Service %s not found\n",
888 _dbus_string_get_const_data (service_name));
890 _dbus_verbose ("Service %s found\n",
891 _dbus_string_get_const_data (service_name));
893 return BUS_SID_FROM_SELINUX (sid);
894 #endif /* HAVE_SELINUX */
899 * Get the SELinux policy root. This is used to find the D-Bus
900 * specific config file within the policy.
903 bus_selinux_get_policy_root (void)
906 return selinux_policy_root ();
909 #endif /* HAVE_SELINUX */
913 * For debugging: Print out the current hash table of service SIDs.
916 bus_selinux_id_table_print (DBusHashTable *service_table)
918 #ifdef DBUS_ENABLE_VERBOSE_MODE
922 if (!selinux_enabled)
925 _dbus_verbose ("Service SID Table:\n");
926 _dbus_hash_iter_init (service_table, &iter);
927 while (_dbus_hash_iter_next (&iter))
929 const char *key = _dbus_hash_iter_get_string_key (&iter);
930 security_id_t sid = _dbus_hash_iter_get_value (&iter);
931 _dbus_verbose ("The key is %s\n", key);
932 _dbus_verbose ("The context is %s\n", sid->ctx);
933 _dbus_verbose ("The refcount is %d\n", sid->refcnt);
935 #endif /* HAVE_SELINUX */
936 #endif /* DBUS_ENABLE_VERBOSE_MODE */
940 #ifdef DBUS_ENABLE_VERBOSE_MODE
943 * Print out some AVC statistics.
946 bus_avc_print_stats (void)
948 struct avc_cache_stats cstats;
950 if (!selinux_enabled)
953 _dbus_verbose ("AVC Statistics:\n");
954 avc_cache_stats (&cstats);
956 _dbus_verbose ("AVC Cache Statistics:\n");
957 _dbus_verbose ("Entry lookups: %d\n", cstats.entry_lookups);
958 _dbus_verbose ("Entry hits: %d\n", cstats.entry_hits);
959 _dbus_verbose ("Entry misses %d\n", cstats.entry_misses);
960 _dbus_verbose ("Entry discards: %d\n", cstats.entry_discards);
961 _dbus_verbose ("CAV lookups: %d\n", cstats.cav_lookups);
962 _dbus_verbose ("CAV hits: %d\n", cstats.cav_hits);
963 _dbus_verbose ("CAV probes: %d\n", cstats.cav_probes);
964 _dbus_verbose ("CAV misses: %d\n", cstats.cav_misses);
966 #endif /* HAVE_SELINUX */
967 #endif /* DBUS_ENABLE_VERBOSE_MODE */
971 * Destroy the AVC before we terminate.
974 bus_selinux_shutdown (void)
977 if (!selinux_enabled)
980 _dbus_verbose ("AVC shutdown\n");
982 if (bus_sid != SECSID_WILD)
985 bus_sid = SECSID_WILD;
987 #ifdef DBUS_ENABLE_VERBOSE_MODE
989 if (_dbus_is_verbose())
990 bus_avc_print_stats ();
992 #endif /* DBUS_ENABLE_VERBOSE_MODE */
996 audit_close (audit_fd);
997 #endif /* HAVE_LIBAUDIT */
999 #endif /* HAVE_SELINUX */