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;
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;
181 _dbus_string_copy_to_buffer (audmsg, buf, bufleft);
185 * Create thread to notify the AVC of enforcing and policy reload
186 * changes via netlink.
188 * @param run the thread run function
189 * @return pointer to the thread
192 avc_create_thread (void (*run) (void))
196 rc = pthread_create (&avc_notify_thread, NULL, (void *(*) (void *)) run, NULL);
199 _dbus_warn ("Failed to start AVC thread: %s\n", _dbus_strerror (rc));
202 return &avc_notify_thread;
205 /* Stop AVC netlink thread. */
207 avc_stop_thread (void *thread)
209 pthread_cancel (*(pthread_t *) thread);
212 /* Allocate a new AVC lock. */
214 avc_alloc_lock (void)
216 pthread_mutex_t *avc_mutex;
218 avc_mutex = dbus_new (pthread_mutex_t, 1);
219 if (avc_mutex == NULL)
221 _dbus_warn ("Could not create mutex: %s\n", _dbus_strerror (errno));
224 pthread_mutex_init (avc_mutex, NULL);
229 /* Acquire an AVC lock. */
231 avc_get_lock (void *lock)
233 pthread_mutex_lock (lock);
236 /* Release an AVC lock. */
238 avc_release_lock (void *lock)
240 pthread_mutex_unlock (lock);
243 /* Free an AVC lock. */
245 avc_free_lock (void *lock)
247 pthread_mutex_destroy (lock);
250 #endif /* HAVE_SELINUX */
253 * Return whether or not SELinux is enabled; must be
254 * called after bus_selinux_init.
257 bus_selinux_enabled (void)
260 return selinux_enabled;
263 #endif /* HAVE_SELINUX */
267 * Do early initialization; determine whether SELinux is enabled.
270 bus_selinux_pre_init (void)
274 _dbus_assert (bus_sid == SECSID_WILD);
276 /* Determine if we are running an SELinux kernel. */
277 r = is_selinux_enabled ();
280 _dbus_warn ("Could not tell if SELinux is enabled: %s\n",
281 _dbus_strerror (errno));
285 selinux_enabled = r != 0;
293 * Initialize the user space access vector cache (AVC) for D-Bus and set up
297 bus_selinux_full_init (void)
302 _dbus_assert (bus_sid == SECSID_WILD);
304 if (!selinux_enabled)
306 _dbus_verbose ("SELinux not enabled in this kernel.\n");
310 _dbus_verbose ("SELinux is enabled in this kernel.\n");
312 avc_entry_ref_init (&aeref);
313 if (avc_init ("avc", &mem_cb, &log_cb, &thread_cb, &lock_cb) < 0)
315 _dbus_warn ("Failed to start Access Vector Cache (AVC).\n");
320 openlog ("dbus", LOG_PERROR, LOG_USER);
321 _dbus_verbose ("Access Vector Cache (AVC) started.\n");
324 if (avc_add_callback (policy_reload_callback, AVC_CALLBACK_RESET,
325 NULL, NULL, 0, 0) < 0)
327 _dbus_warn ("Failed to add policy reload callback: %s\n",
328 _dbus_strerror (errno));
334 bus_sid = SECSID_WILD;
336 if (getcon (&bus_context) < 0)
338 _dbus_verbose ("Error getting context of bus: %s\n",
339 _dbus_strerror (errno));
343 if (avc_context_to_sid (bus_context, &bus_sid) < 0)
345 _dbus_verbose ("Error getting SID from bus context: %s\n",
346 _dbus_strerror (errno));
347 freecon (bus_context);
351 freecon (bus_context);
353 #endif /* HAVE_SELINUX */
358 * Decrement SID reference count.
360 * @param sid the SID to decrement
363 bus_selinux_id_unref (BusSELinuxID *sid)
366 if (!selinux_enabled)
369 _dbus_assert (sid != NULL);
371 sidput (SELINUX_SID_FROM_BUS (sid));
372 #endif /* HAVE_SELINUX */
376 bus_selinux_id_ref (BusSELinuxID *sid)
379 if (!selinux_enabled)
382 _dbus_assert (sid != NULL);
384 sidget (SELINUX_SID_FROM_BUS (sid));
385 #endif /* HAVE_SELINUX */
389 * Determine if the SELinux security policy allows the given sender
390 * security context to go to the given recipient security context.
391 * This function determines if the requested permissions are to be
392 * granted from the connection to the message bus or to another
393 * optionally supplied security identifier (e.g. for a service
394 * context). Currently these permissions are either send_msg or
395 * acquire_svc in the dbus class.
397 * @param sender_sid source security context
398 * @param override_sid is the target security context. If SECSID_WILD this will
399 * use the context of the bus itself (e.g. the default).
400 * @param target_class is the target security class.
401 * @param requested is the requested permissions.
402 * @returns #TRUE if security policy allows the send.
406 bus_selinux_check (BusSELinuxID *sender_sid,
407 BusSELinuxID *override_sid,
408 security_class_t target_class,
409 access_vector_t requested,
412 if (!selinux_enabled)
415 /* Make the security check. AVC checks enforcing mode here as well. */
416 if (avc_has_perm (SELINUX_SID_FROM_BUS (sender_sid),
418 SELINUX_SID_FROM_BUS (override_sid) :
419 SELINUX_SID_FROM_BUS (bus_sid),
420 target_class, requested, &aeref, auxdata) < 0)
422 _dbus_verbose ("SELinux denying due to security policy.\n");
428 #endif /* HAVE_SELINUX */
431 * Returns true if the given connection can acquire a service,
432 * assuming the given security ID is needed for that service.
434 * @param connection connection that wants to own the service
435 * @param service_sid the SID of the service from the table
436 * @returns #TRUE if acquire is permitted.
439 bus_selinux_allows_acquire_service (DBusConnection *connection,
440 BusSELinuxID *service_sid,
441 const char *service_name,
445 BusSELinuxID *connection_sid;
450 if (!selinux_enabled)
453 connection_sid = bus_connection_get_selinux_id (connection);
454 if (!dbus_connection_get_unix_process_id (connection, &spid))
457 if (!_dbus_string_init (&auxdata))
460 if (!_dbus_string_append (&auxdata, "service="))
463 if (!_dbus_string_append (&auxdata, service_name))
468 if (!_dbus_string_append (&auxdata, " spid="))
471 if (!_dbus_string_append_uint (&auxdata, spid))
475 ret = bus_selinux_check (connection_sid,
481 _dbus_string_free (&auxdata);
485 _dbus_string_free (&auxdata);
491 #endif /* HAVE_SELINUX */
495 * Check if SELinux security controls allow the message to be sent to a
496 * particular connection based on the security context of the sender and
497 * that of the receiver. The destination connection need not be the
498 * addressed recipient, it could be an "eavesdropper"
500 * @param sender the sender of the message.
501 * @param proposed_recipient the connection the message is to be sent to.
502 * @returns whether to allow the send
505 bus_selinux_allows_send (DBusConnection *sender,
506 DBusConnection *proposed_recipient,
508 const char *interface,
510 const char *error_name,
511 const char *destination,
515 BusSELinuxID *recipient_sid;
516 BusSELinuxID *sender_sid;
517 unsigned long spid, tpid;
520 dbus_bool_t string_alloced;
522 if (!selinux_enabled)
525 if (!sender || !dbus_connection_get_unix_process_id (sender, &spid))
527 if (!proposed_recipient || !dbus_connection_get_unix_process_id (proposed_recipient, &tpid))
530 string_alloced = FALSE;
531 if (!_dbus_string_init (&auxdata))
533 string_alloced = TRUE;
535 if (!_dbus_string_append (&auxdata, "msgtype="))
538 if (!_dbus_string_append (&auxdata, msgtype))
543 if (!_dbus_string_append (&auxdata, " interface="))
545 if (!_dbus_string_append (&auxdata, interface))
551 if (!_dbus_string_append (&auxdata, " member="))
553 if (!_dbus_string_append (&auxdata, member))
559 if (!_dbus_string_append (&auxdata, " error_name="))
561 if (!_dbus_string_append (&auxdata, error_name))
567 if (!_dbus_string_append (&auxdata, " dest="))
569 if (!_dbus_string_append (&auxdata, destination))
575 if (!_dbus_string_append (&auxdata, " spid="))
578 if (!_dbus_string_append_uint (&auxdata, spid))
584 if (!_dbus_string_append (&auxdata, " tpid="))
587 if (!_dbus_string_append_uint (&auxdata, tpid))
591 sender_sid = bus_connection_get_selinux_id (sender);
592 /* A NULL proposed_recipient means the bus itself. */
593 if (proposed_recipient)
594 recipient_sid = bus_connection_get_selinux_id (proposed_recipient);
596 recipient_sid = BUS_SID_FROM_SELINUX (bus_sid);
598 ret = bus_selinux_check (sender_sid,
604 _dbus_string_free (&auxdata);
610 _dbus_string_free (&auxdata);
616 #endif /* HAVE_SELINUX */
620 bus_selinux_append_context (DBusMessage *message,
627 if (avc_sid_to_context (SELINUX_SID_FROM_BUS (sid), &context) < 0)
632 dbus_set_error (error, DBUS_ERROR_FAILED,
633 "Error getting context from SID: %s\n",
634 _dbus_strerror (errno));
637 if (!dbus_message_append_args (message,
644 _DBUS_SET_OOM (error);
655 * Gets the security context of a connection to the bus. It is up to
656 * the caller to freecon() when they are done.
658 * @param connection the connection to get the context of.
659 * @param con the location to store the security context.
660 * @returns #TRUE if context is successfully obtained.
664 bus_connection_read_selinux_context (DBusConnection *connection,
669 if (!selinux_enabled)
672 _dbus_assert (connection != NULL);
674 if (!dbus_connection_get_unix_fd (connection, &fd))
676 _dbus_verbose ("Failed to get file descriptor of socket.\n");
680 if (getpeercon (fd, con) < 0)
682 _dbus_verbose ("Error getting context of socket peer: %s\n",
683 _dbus_strerror (errno));
687 _dbus_verbose ("Successfully read connection context.\n");
690 #endif /* HAVE_SELINUX */
693 * Read the SELinux ID from the connection.
695 * @param connection the connection to read from
696 * @returns the SID if successfully determined, #NULL otherwise.
699 bus_selinux_init_connection_id (DBusConnection *connection,
706 if (!selinux_enabled)
709 if (!bus_connection_read_selinux_context (connection, &con))
711 dbus_set_error (error, DBUS_ERROR_FAILED,
712 "Failed to read an SELinux context from connection");
713 _dbus_verbose ("Error getting peer context.\n");
717 _dbus_verbose ("Converting context to SID to store on connection\n");
719 if (avc_context_to_sid (con, &sid) < 0)
724 dbus_set_error (error, DBUS_ERROR_FAILED,
725 "Error getting SID from context \"%s\": %s\n",
726 con, _dbus_strerror (errno));
728 _dbus_warn ("Error getting SID from context \"%s\": %s\n",
729 con, _dbus_strerror (errno));
736 return BUS_SID_FROM_SELINUX (sid);
739 #endif /* HAVE_SELINUX */
744 * Function for freeing hash table data. These SIDs
745 * should no longer be referenced.
748 bus_selinux_id_table_free_value (BusSELinuxID *sid)
751 /* NULL sometimes due to how DBusHashTable works */
753 bus_selinux_id_unref (sid);
754 #endif /* HAVE_SELINUX */
758 * Creates a new table mapping service names to security ID.
759 * A security ID is a "compiled" security context, a security
760 * context is just a string.
762 * @returns the new table or #NULL if no memory
765 bus_selinux_id_table_new (void)
767 return _dbus_hash_table_new (DBUS_HASH_STRING,
768 (DBusFreeFunction) dbus_free,
769 (DBusFreeFunction) bus_selinux_id_table_free_value);
773 * Hashes a service name and service context into the service SID
774 * table as a string and a SID.
776 * @param service_name is the name of the service.
777 * @param service_context is the context of the service.
778 * @param service_table is the table to hash them into.
779 * @return #FALSE if not enough memory
782 bus_selinux_id_table_insert (DBusHashTable *service_table,
783 const char *service_name,
784 const char *service_context)
791 if (!selinux_enabled)
797 key = _dbus_strdup (service_name);
801 if (avc_context_to_sid ((char *) service_context, &sid) < 0)
809 _dbus_warn ("Error getting SID from context \"%s\": %s\n",
810 (char *) service_context,
811 _dbus_strerror (errno));
815 if (!_dbus_hash_table_insert_string (service_table,
817 BUS_SID_FROM_SELINUX (sid)))
820 _dbus_verbose ("Parsed \tservice: %s \n\t\tcontext: %s\n",
824 /* These are owned by the hash, so clear them to avoid unref */
831 if (sid != SECSID_WILD)
840 #endif /* HAVE_SELINUX */
845 * Find the security identifier associated with a particular service
846 * name. Return a pointer to this SID, or #NULL/SECSID_WILD if the
847 * service is not found in the hash table. This should be nearly a
848 * constant time operation. If SELinux support is not available,
849 * always return NULL.
851 * @param service_table the hash table to check for service name.
852 * @param service_name the name of the service to look for.
853 * @returns the SELinux ID associated with the service
856 bus_selinux_id_table_lookup (DBusHashTable *service_table,
857 const DBusString *service_name)
862 sid = SECSID_WILD; /* default context */
864 if (!selinux_enabled)
867 _dbus_verbose ("Looking up service SID for %s\n",
868 _dbus_string_get_const_data (service_name));
870 sid = _dbus_hash_table_lookup_string (service_table,
871 _dbus_string_get_const_data (service_name));
873 if (sid == SECSID_WILD)
874 _dbus_verbose ("Service %s not found\n",
875 _dbus_string_get_const_data (service_name));
877 _dbus_verbose ("Service %s found\n",
878 _dbus_string_get_const_data (service_name));
880 return BUS_SID_FROM_SELINUX (sid);
881 #endif /* HAVE_SELINUX */
886 * Get the SELinux policy root. This is used to find the D-Bus
887 * specific config file within the policy.
890 bus_selinux_get_policy_root (void)
893 return selinux_policy_root ();
896 #endif /* HAVE_SELINUX */
900 * For debugging: Print out the current hash table of service SIDs.
903 bus_selinux_id_table_print (DBusHashTable *service_table)
905 #ifdef DBUS_ENABLE_VERBOSE_MODE
909 if (!selinux_enabled)
912 _dbus_verbose ("Service SID Table:\n");
913 _dbus_hash_iter_init (service_table, &iter);
914 while (_dbus_hash_iter_next (&iter))
916 const char *key = _dbus_hash_iter_get_string_key (&iter);
917 security_id_t sid = _dbus_hash_iter_get_value (&iter);
918 _dbus_verbose ("The key is %s\n", key);
919 _dbus_verbose ("The context is %s\n", sid->ctx);
920 _dbus_verbose ("The refcount is %d\n", sid->refcnt);
922 #endif /* HAVE_SELINUX */
923 #endif /* DBUS_ENABLE_VERBOSE_MODE */
927 #ifdef DBUS_ENABLE_VERBOSE_MODE
930 * Print out some AVC statistics.
933 bus_avc_print_stats (void)
935 struct avc_cache_stats cstats;
937 if (!selinux_enabled)
940 _dbus_verbose ("AVC Statistics:\n");
941 avc_cache_stats (&cstats);
943 _dbus_verbose ("AVC Cache Statistics:\n");
944 _dbus_verbose ("Entry lookups: %d\n", cstats.entry_lookups);
945 _dbus_verbose ("Entry hits: %d\n", cstats.entry_hits);
946 _dbus_verbose ("Entry misses %d\n", cstats.entry_misses);
947 _dbus_verbose ("Entry discards: %d\n", cstats.entry_discards);
948 _dbus_verbose ("CAV lookups: %d\n", cstats.cav_lookups);
949 _dbus_verbose ("CAV hits: %d\n", cstats.cav_hits);
950 _dbus_verbose ("CAV probes: %d\n", cstats.cav_probes);
951 _dbus_verbose ("CAV misses: %d\n", cstats.cav_misses);
953 #endif /* HAVE_SELINUX */
954 #endif /* DBUS_ENABLE_VERBOSE_MODE */
958 * Destroy the AVC before we terminate.
961 bus_selinux_shutdown (void)
964 if (!selinux_enabled)
967 _dbus_verbose ("AVC shutdown\n");
969 if (bus_sid != SECSID_WILD)
972 bus_sid = SECSID_WILD;
974 #ifdef DBUS_ENABLE_VERBOSE_MODE
976 if (_dbus_is_verbose())
977 bus_avc_print_stats ();
979 #endif /* DBUS_ENABLE_VERBOSE_MODE */
983 audit_close (audit_fd);
984 #endif /* HAVE_LIBAUDIT */
986 #endif /* HAVE_SELINUX */