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>
35 #include "config-parser.h"
41 #include <sys/types.h>
46 #include <selinux/selinux.h>
47 #include <selinux/avc.h>
52 #endif /* HAVE_SELINUX */
55 #endif /* HAVE_LIBAUDIT */
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 log_callback (const char *fmt, ...)
129 audit_fd = bus_audit_get_fd ();
133 /* This should really be a DBusString, but DBusString allocates
134 * memory dynamically; before switching it, we need to check with
135 * SELinux people that it would be OK for this to fall back to
136 * syslog if OOM, like the equivalent AppArmor code does. */
137 char buf[PATH_MAX*2];
139 /* FIXME: need to change this to show real user */
140 vsnprintf(buf, sizeof(buf), fmt, ap);
141 audit_log_user_avc_message(audit_fd, AUDIT_USER_AVC, buf, NULL, NULL,
145 #endif /* HAVE_LIBAUDIT */
147 vsyslog (LOG_USER | LOG_INFO, fmt, ap);
154 * On a policy reload we need to reparse the SELinux configuration file, since
155 * this could have changed. Send a SIGHUP to reload all configs.
158 policy_reload_callback (u_int32_t event, security_id_t ssid,
159 security_id_t tsid, security_class_t tclass,
160 access_vector_t perms, access_vector_t *out_retained)
162 if (event == AVC_CALLBACK_RESET)
163 return raise (SIGHUP);
169 * Log any auxiliary data
172 log_audit_callback (void *data, security_class_t class, char *buf, size_t bufleft)
174 DBusString *audmsg = data;
176 if (bufleft > (size_t) _dbus_string_get_length(audmsg))
178 _dbus_string_copy_to_buffer_with_nul (audmsg, buf, bufleft);
184 _dbus_string_init_const(&s, "Buffer too small for audit message");
186 if (bufleft > (size_t) _dbus_string_get_length(&s))
187 _dbus_string_copy_to_buffer_with_nul (&s, buf, bufleft);
192 * Create thread to notify the AVC of enforcing and policy reload
193 * changes via netlink.
195 * @param run the thread run function
196 * @return pointer to the thread
199 avc_create_thread (void (*run) (void))
203 rc = pthread_create (&avc_notify_thread, NULL, (void *(*) (void *)) run, NULL);
206 _dbus_warn ("Failed to start AVC thread: %s\n", _dbus_strerror (rc));
209 return &avc_notify_thread;
212 /* Stop AVC netlink thread. */
214 avc_stop_thread (void *thread)
216 pthread_cancel (*(pthread_t *) thread);
219 /* Allocate a new AVC lock. */
221 avc_alloc_lock (void)
223 pthread_mutex_t *avc_mutex;
225 avc_mutex = dbus_new (pthread_mutex_t, 1);
226 if (avc_mutex == NULL)
228 _dbus_warn ("Could not create mutex: %s\n", _dbus_strerror (errno));
231 pthread_mutex_init (avc_mutex, NULL);
236 /* Acquire an AVC lock. */
238 avc_get_lock (void *lock)
240 pthread_mutex_lock (lock);
243 /* Release an AVC lock. */
245 avc_release_lock (void *lock)
247 pthread_mutex_unlock (lock);
250 /* Free an AVC lock. */
252 avc_free_lock (void *lock)
254 pthread_mutex_destroy (lock);
257 #endif /* HAVE_SELINUX */
260 * Return whether or not SELinux is enabled; must be
261 * called after bus_selinux_init.
264 bus_selinux_enabled (void)
267 return selinux_enabled;
270 #endif /* HAVE_SELINUX */
274 * Do early initialization; determine whether SELinux is enabled.
277 bus_selinux_pre_init (void)
281 _dbus_assert (bus_sid == SECSID_WILD);
283 /* Determine if we are running an SELinux kernel. */
284 r = is_selinux_enabled ();
287 _dbus_warn ("Could not tell if SELinux is enabled: %s\n",
288 _dbus_strerror (errno));
292 selinux_enabled = r != 0;
300 * Private Flask definitions; the order of these constants must
301 * exactly match that of the structure array below!
303 /* security dbus class constants */
304 #define SECCLASS_DBUS 1
306 /* dbus's per access vector constants */
307 #define DBUS__ACQUIRE_SVC 1
308 #define DBUS__SEND_MSG 2
311 static struct security_class_mapping dbus_map[] = {
312 { "dbus", { "acquire_svc", "send_msg", NULL } },
315 #endif /* HAVE_SELINUX */
318 * Establish dynamic object class and permission mapping and
319 * initialize the user space access vector cache (AVC) for D-Bus and set up
323 bus_selinux_full_init (void)
328 _dbus_assert (bus_sid == SECSID_WILD);
330 if (!selinux_enabled)
332 _dbus_verbose ("SELinux not enabled in this kernel.\n");
336 _dbus_verbose ("SELinux is enabled in this kernel.\n");
338 if (selinux_set_mapping (dbus_map) < 0)
340 _dbus_warn ("Failed to set up security class mapping (selinux_set_mapping():%s).\n",
345 avc_entry_ref_init (&aeref);
346 if (avc_init ("avc", &mem_cb, &log_cb, &thread_cb, &lock_cb) < 0)
348 _dbus_warn ("Failed to start Access Vector Cache (AVC).\n");
353 _dbus_verbose ("Access Vector Cache (AVC) started.\n");
356 if (avc_add_callback (policy_reload_callback, AVC_CALLBACK_RESET,
357 NULL, NULL, 0, 0) < 0)
359 _dbus_warn ("Failed to add policy reload callback: %s\n",
360 _dbus_strerror (errno));
366 bus_sid = SECSID_WILD;
368 if (getcon (&bus_context) < 0)
370 _dbus_verbose ("Error getting context of bus: %s\n",
371 _dbus_strerror (errno));
375 if (avc_context_to_sid (bus_context, &bus_sid) < 0)
377 _dbus_verbose ("Error getting SID from bus context: %s\n",
378 _dbus_strerror (errno));
379 freecon (bus_context);
383 freecon (bus_context);
385 #endif /* HAVE_SELINUX */
390 * Decrement SID reference count.
392 * @param sid the SID to decrement
395 bus_selinux_id_unref (BusSELinuxID *sid)
398 if (!selinux_enabled)
401 _dbus_assert (sid != NULL);
403 sidput (SELINUX_SID_FROM_BUS (sid));
404 #endif /* HAVE_SELINUX */
408 bus_selinux_id_ref (BusSELinuxID *sid)
411 if (!selinux_enabled)
414 _dbus_assert (sid != NULL);
416 sidget (SELINUX_SID_FROM_BUS (sid));
417 #endif /* HAVE_SELINUX */
421 * Determine if the SELinux security policy allows the given sender
422 * security context to go to the given recipient security context.
423 * This function determines if the requested permissions are to be
424 * granted from the connection to the message bus or to another
425 * optionally supplied security identifier (e.g. for a service
426 * context). Currently these permissions are either send_msg or
427 * acquire_svc in the dbus class.
429 * @param sender_sid source security context
430 * @param override_sid is the target security context. If SECSID_WILD this will
431 * use the context of the bus itself (e.g. the default).
432 * @param target_class is the target security class.
433 * @param requested is the requested permissions.
434 * @returns #TRUE if security policy allows the send.
438 bus_selinux_check (BusSELinuxID *sender_sid,
439 BusSELinuxID *override_sid,
440 security_class_t target_class,
441 access_vector_t requested,
444 if (!selinux_enabled)
447 /* Make the security check. AVC checks enforcing mode here as well. */
448 if (avc_has_perm (SELINUX_SID_FROM_BUS (sender_sid),
450 SELINUX_SID_FROM_BUS (override_sid) :
451 SELINUX_SID_FROM_BUS (bus_sid),
452 target_class, requested, &aeref, auxdata) < 0)
457 _dbus_verbose ("SELinux denying due to security policy.\n");
460 _dbus_verbose ("SELinux denying due to invalid security context.\n");
463 _dbus_verbose ("SELinux denying due to: %s\n", _dbus_strerror (errno));
470 #endif /* HAVE_SELINUX */
473 * Returns true if the given connection can acquire a service,
474 * assuming the given security ID is needed for that service.
476 * @param connection connection that wants to own the service
477 * @param service_sid the SID of the service from the table
478 * @returns #TRUE if acquire is permitted.
481 bus_selinux_allows_acquire_service (DBusConnection *connection,
482 BusSELinuxID *service_sid,
483 const char *service_name,
487 BusSELinuxID *connection_sid;
492 if (!selinux_enabled)
495 connection_sid = bus_connection_get_selinux_id (connection);
496 if (!dbus_connection_get_unix_process_id (connection, &spid))
499 if (!_dbus_string_init (&auxdata))
502 if (!_dbus_string_append (&auxdata, "service="))
505 if (!_dbus_string_append (&auxdata, service_name))
510 if (!_dbus_string_append (&auxdata, " spid="))
513 if (!_dbus_string_append_uint (&auxdata, spid))
517 ret = bus_selinux_check (connection_sid,
523 _dbus_string_free (&auxdata);
527 _dbus_string_free (&auxdata);
533 #endif /* HAVE_SELINUX */
537 * Check if SELinux security controls allow the message to be sent to a
538 * particular connection based on the security context of the sender and
539 * that of the receiver. The destination connection need not be the
540 * addressed recipient, it could be an "eavesdropper"
542 * @param sender the sender of the message.
543 * @param proposed_recipient the connection the message is to be sent to.
544 * @returns whether to allow the send
547 bus_selinux_allows_send (DBusConnection *sender,
548 DBusConnection *proposed_recipient,
550 const char *interface,
552 const char *error_name,
553 const char *destination,
557 BusSELinuxID *recipient_sid;
558 BusSELinuxID *sender_sid;
559 unsigned long spid, tpid;
562 dbus_bool_t string_alloced;
564 if (!selinux_enabled)
567 if (!sender || !dbus_connection_get_unix_process_id (sender, &spid))
569 if (!proposed_recipient || !dbus_connection_get_unix_process_id (proposed_recipient, &tpid))
572 string_alloced = FALSE;
573 if (!_dbus_string_init (&auxdata))
575 string_alloced = TRUE;
577 if (!_dbus_string_append (&auxdata, "msgtype="))
580 if (!_dbus_string_append (&auxdata, msgtype))
585 if (!_dbus_string_append (&auxdata, " interface="))
587 if (!_dbus_string_append (&auxdata, interface))
593 if (!_dbus_string_append (&auxdata, " member="))
595 if (!_dbus_string_append (&auxdata, member))
601 if (!_dbus_string_append (&auxdata, " error_name="))
603 if (!_dbus_string_append (&auxdata, error_name))
609 if (!_dbus_string_append (&auxdata, " dest="))
611 if (!_dbus_string_append (&auxdata, destination))
617 if (!_dbus_string_append (&auxdata, " spid="))
620 if (!_dbus_string_append_uint (&auxdata, spid))
626 if (!_dbus_string_append (&auxdata, " tpid="))
629 if (!_dbus_string_append_uint (&auxdata, tpid))
633 sender_sid = bus_connection_get_selinux_id (sender);
634 /* A NULL proposed_recipient means the bus itself. */
635 if (proposed_recipient)
636 recipient_sid = bus_connection_get_selinux_id (proposed_recipient);
638 recipient_sid = BUS_SID_FROM_SELINUX (bus_sid);
640 ret = bus_selinux_check (sender_sid,
646 _dbus_string_free (&auxdata);
652 _dbus_string_free (&auxdata);
658 #endif /* HAVE_SELINUX */
662 bus_selinux_append_context (DBusMessage *message,
669 if (avc_sid_to_context (SELINUX_SID_FROM_BUS (sid), &context) < 0)
674 dbus_set_error (error, DBUS_ERROR_FAILED,
675 "Error getting context from SID: %s\n",
676 _dbus_strerror (errno));
679 if (!dbus_message_append_args (message,
686 _DBUS_SET_OOM (error);
697 * Gets the security context of a connection to the bus. It is up to
698 * the caller to freecon() when they are done.
700 * @param connection the connection to get the context of.
701 * @param con the location to store the security context.
702 * @returns #TRUE if context is successfully obtained.
706 bus_connection_read_selinux_context (DBusConnection *connection,
711 if (!selinux_enabled)
714 _dbus_assert (connection != NULL);
716 if (!dbus_connection_get_unix_fd (connection, &fd))
718 _dbus_verbose ("Failed to get file descriptor of socket.\n");
722 if (getpeercon (fd, con) < 0)
724 _dbus_verbose ("Error getting context of socket peer: %s\n",
725 _dbus_strerror (errno));
729 _dbus_verbose ("Successfully read connection context.\n");
732 #endif /* HAVE_SELINUX */
735 * Read the SELinux ID from the connection.
737 * @param connection the connection to read from
738 * @returns the SID if successfully determined, #NULL otherwise.
741 bus_selinux_init_connection_id (DBusConnection *connection,
748 if (!selinux_enabled)
751 if (!bus_connection_read_selinux_context (connection, &con))
753 dbus_set_error (error, DBUS_ERROR_FAILED,
754 "Failed to read an SELinux context from connection");
755 _dbus_verbose ("Error getting peer context.\n");
759 _dbus_verbose ("Converting context to SID to store on connection\n");
761 if (avc_context_to_sid (con, &sid) < 0)
766 dbus_set_error (error, DBUS_ERROR_FAILED,
767 "Error getting SID from context \"%s\": %s\n",
768 con, _dbus_strerror (errno));
770 _dbus_warn ("Error getting SID from context \"%s\": %s\n",
771 con, _dbus_strerror (errno));
778 return BUS_SID_FROM_SELINUX (sid);
781 #endif /* HAVE_SELINUX */
786 * Function for freeing hash table data. These SIDs
787 * should no longer be referenced.
790 bus_selinux_id_table_free_value (BusSELinuxID *sid)
793 /* NULL sometimes due to how DBusHashTable works */
795 bus_selinux_id_unref (sid);
796 #endif /* HAVE_SELINUX */
800 * Creates a new table mapping service names to security ID.
801 * A security ID is a "compiled" security context, a security
802 * context is just a string.
804 * @returns the new table or #NULL if no memory
807 bus_selinux_id_table_new (void)
809 return _dbus_hash_table_new (DBUS_HASH_STRING,
810 (DBusFreeFunction) dbus_free,
811 (DBusFreeFunction) bus_selinux_id_table_free_value);
815 * Hashes a service name and service context into the service SID
816 * table as a string and a SID.
818 * @param service_name is the name of the service.
819 * @param service_context is the context of the service.
820 * @param service_table is the table to hash them into.
821 * @return #FALSE if not enough memory
824 bus_selinux_id_table_insert (DBusHashTable *service_table,
825 const char *service_name,
826 const char *service_context)
833 if (!selinux_enabled)
839 key = _dbus_strdup (service_name);
843 if (avc_context_to_sid ((char *) service_context, &sid) < 0)
851 _dbus_warn ("Error getting SID from context \"%s\": %s\n",
852 (char *) service_context,
853 _dbus_strerror (errno));
857 if (!_dbus_hash_table_insert_string (service_table,
859 BUS_SID_FROM_SELINUX (sid)))
862 _dbus_verbose ("Parsed \tservice: %s \n\t\tcontext: %s\n",
866 /* These are owned by the hash, so clear them to avoid unref */
873 if (sid != SECSID_WILD)
882 #endif /* HAVE_SELINUX */
887 * Find the security identifier associated with a particular service
888 * name. Return a pointer to this SID, or #NULL/SECSID_WILD if the
889 * service is not found in the hash table. This should be nearly a
890 * constant time operation. If SELinux support is not available,
891 * always return NULL.
893 * @param service_table the hash table to check for service name.
894 * @param service_name the name of the service to look for.
895 * @returns the SELinux ID associated with the service
898 bus_selinux_id_table_lookup (DBusHashTable *service_table,
899 const DBusString *service_name)
904 sid = SECSID_WILD; /* default context */
906 if (!selinux_enabled)
909 _dbus_verbose ("Looking up service SID for %s\n",
910 _dbus_string_get_const_data (service_name));
912 sid = _dbus_hash_table_lookup_string (service_table,
913 _dbus_string_get_const_data (service_name));
915 if (sid == SECSID_WILD)
916 _dbus_verbose ("Service %s not found\n",
917 _dbus_string_get_const_data (service_name));
919 _dbus_verbose ("Service %s found\n",
920 _dbus_string_get_const_data (service_name));
922 return BUS_SID_FROM_SELINUX (sid);
923 #endif /* HAVE_SELINUX */
928 * Get the SELinux policy root. This is used to find the D-Bus
929 * specific config file within the policy.
932 bus_selinux_get_policy_root (void)
935 return selinux_policy_root ();
938 #endif /* HAVE_SELINUX */
942 * For debugging: Print out the current hash table of service SIDs.
945 bus_selinux_id_table_print (DBusHashTable *service_table)
947 #if defined (DBUS_ENABLE_VERBOSE_MODE) && defined (HAVE_SELINUX)
950 if (!selinux_enabled)
953 _dbus_verbose ("Service SID Table:\n");
954 _dbus_hash_iter_init (service_table, &iter);
955 while (_dbus_hash_iter_next (&iter))
957 const char *key = _dbus_hash_iter_get_string_key (&iter);
958 security_id_t sid = _dbus_hash_iter_get_value (&iter);
959 _dbus_verbose ("The key is %s\n", key);
960 _dbus_verbose ("The context is %s\n", sid->ctx);
961 _dbus_verbose ("The refcount is %d\n", sid->refcnt);
963 #endif /* DBUS_ENABLE_VERBOSE_MODE && HAVE_SELINUX */
968 * Print out some AVC statistics.
972 bus_avc_print_stats (void)
974 #ifdef DBUS_ENABLE_VERBOSE_MODE
975 struct avc_cache_stats cstats;
977 if (!selinux_enabled)
980 _dbus_verbose ("AVC Statistics:\n");
981 avc_cache_stats (&cstats);
983 _dbus_verbose ("AVC Cache Statistics:\n");
984 _dbus_verbose ("Entry lookups: %d\n", cstats.entry_lookups);
985 _dbus_verbose ("Entry hits: %d\n", cstats.entry_hits);
986 _dbus_verbose ("Entry misses %d\n", cstats.entry_misses);
987 _dbus_verbose ("Entry discards: %d\n", cstats.entry_discards);
988 _dbus_verbose ("CAV lookups: %d\n", cstats.cav_lookups);
989 _dbus_verbose ("CAV hits: %d\n", cstats.cav_hits);
990 _dbus_verbose ("CAV probes: %d\n", cstats.cav_probes);
991 _dbus_verbose ("CAV misses: %d\n", cstats.cav_misses);
992 #endif /* DBUS_ENABLE_VERBOSE_MODE */
994 #endif /* HAVE_SELINUX */
997 * Destroy the AVC before we terminate.
1000 bus_selinux_shutdown (void)
1003 if (!selinux_enabled)
1006 _dbus_verbose ("AVC shutdown\n");
1008 if (bus_sid != SECSID_WILD)
1011 bus_sid = SECSID_WILD;
1013 bus_avc_print_stats ();
1017 #endif /* HAVE_SELINUX */