selinux.c 23.7 KB
Newer Older
1
/* -*- mode: C; c-file-style: "gnu" -*-
John Palmieri's avatar
John Palmieri committed
2
 * selinux.c  SELinux security checks for D-Bus
3 4 5
 *
 * Author: Matthew Rickard <mjricka@epoch.ncsc.mil>
 *
6
 * Licensed under the Academic Free License version 2.1
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */
#include <dbus/dbus-internals.h>
#include <dbus/dbus-string.h>
#include "selinux.h"
#include "services.h"
#include "policy.h"
28
#include "utils.h"
29 30 31 32
#include "config-parser.h"

#ifdef HAVE_SELINUX
#include <errno.h>
33
#include <pthread.h>
34 35 36 37 38
#include <syslog.h>
#include <selinux/selinux.h>
#include <selinux/avc.h>
#include <selinux/av_permissions.h>
#include <selinux/flask.h>
39
#include <signal.h>
40
#include <stdarg.h>
41 42 43
#ifdef HAVE_LIBAUDIT
#include <libaudit.h>
#endif /* HAVE_LIBAUDIT */
44 45 46 47 48 49 50 51 52 53 54 55
#endif /* HAVE_SELINUX */

#define BUS_SID_FROM_SELINUX(sid)  ((BusSELinuxID*) (sid))
#define SELINUX_SID_FROM_BUS(sid)  ((security_id_t) (sid))

#ifdef HAVE_SELINUX
/* Store the value telling us if SELinux is enabled in the kernel. */
static dbus_bool_t selinux_enabled = FALSE;

/* Store an avc_entry_ref to speed AVC decisions. */
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;
58 59 60 61 62 63

/* Thread to listen for SELinux status changes via netlink. */
static pthread_t avc_notify_thread;

/* Prototypes for AVC callback functions.  */
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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
static void *avc_create_thread (void (*run) (void));
static void avc_stop_thread (void *thread);
static void *avc_alloc_lock (void);
static void avc_get_lock (void *lock);
static void avc_release_lock (void *lock);
static void avc_free_lock (void *lock);

/* AVC callback structures for use in avc_init.  */
static const struct avc_memory_callback mem_cb =
{
  .func_malloc = dbus_malloc,
  .func_free = dbus_free
};
static const struct avc_log_callback log_cb =
{
  .func_log = log_callback,
81
  .func_audit = log_audit_callback
82 83 84 85 86 87 88 89 90 91 92 93 94
};
static const struct avc_thread_callback thread_cb =
{
  .func_create_thread = avc_create_thread,
  .func_stop_thread = avc_stop_thread
};
static const struct avc_lock_callback lock_cb =
{
  .func_alloc_lock = avc_alloc_lock,
  .func_get_lock = avc_get_lock,
  .func_release_lock = avc_release_lock,
  .func_free_lock = avc_free_lock
};
95 96 97 98 99 100 101 102 103 104 105
#endif /* HAVE_SELINUX */

/**
 * Log callback to log denial messages from the AVC.
 * This is used in avc_init.  Logs to both standard
 * error and syslogd.
 *
 * @param fmt the format string
 * @param variable argument list
 */
#ifdef HAVE_SELINUX
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129

#ifdef HAVE_LIBAUDIT
static int audit_fd = -1;
#endif

static void
audit_init(void)
{
#ifdef HAVE_LIBAUDIT  
  audit_fd = audit_open ();

  if (audit_fd < 0)
    {
      /* If kernel doesn't support audit, bail out */
      if (errno == EINVAL || errno == EPROTONOSUPPORT || errno == EAFNOSUPPORT)
        return;
      /* If user bus, bail out */
      if (errno == EPERM && getuid() != 0)
        return;
      _dbus_warn ("Failed opening connection to the audit subsystem");
    }
#endif /* HAVE_LIBAUDIT */
}

130 131 132 133
static void 
log_callback (const char *fmt, ...) 
{
  va_list ap;
134

135
  va_start(ap, fmt);
136 137 138 139 140 141 142 143 144 145 146 147 148 149

#ifdef HAVE_LIBAUDIT
  if (audit_fd >= 0)
  {
    char buf[PATH_MAX*2];
    
    /* FIXME: need to change this to show real user */
    vsnprintf(buf, sizeof(buf), fmt, ap);
    audit_log_user_avc_message(audit_fd, AUDIT_USER_AVC, buf, NULL, NULL,
                               NULL, getuid());
    return;
  }
#endif /* HAVE_LIBAUDIT */
  
150 151 152 153
  vsyslog (LOG_INFO, fmt, ap);
  va_end(ap);
}

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
/**
 * On a policy reload we need to reparse the SELinux configuration file, since
 * this could have changed.  Send a SIGHUP to reload all configs.
 */
static int
policy_reload_callback (u_int32_t event, security_id_t ssid, 
                        security_id_t tsid, security_class_t tclass, 
                        access_vector_t perms, access_vector_t *out_retained)
{
  if (event == AVC_CALLBACK_RESET)
    return raise (SIGHUP);
  
  return 0;
}

169 170 171 172 173 174 175 176 177 178
/**
 * Log any auxiliary data 
 */
static void
log_audit_callback (void *data, security_class_t class, char *buf, size_t bufleft)
{
  DBusString *audmsg = data;
  _dbus_string_copy_to_buffer (audmsg, buf, bufleft);
}

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
/**
 * Create thread to notify the AVC of enforcing and policy reload
 * changes via netlink.
 *
 * @param run the thread run function
 * @return pointer to the thread
 */
static void *
avc_create_thread (void (*run) (void))
{
  int rc;

  rc = pthread_create (&avc_notify_thread, NULL, (void *(*) (void *)) run, NULL);
  if (rc != 0)
    {
      _dbus_warn ("Failed to start AVC thread: %s\n", _dbus_strerror (rc));
      exit (1);
    }
  return &avc_notify_thread;
}

/* Stop AVC netlink thread.  */
static void
avc_stop_thread (void *thread)
{
  pthread_cancel (*(pthread_t *) thread);
}

/* Allocate a new AVC lock.  */
static void *
avc_alloc_lock (void)
{
  pthread_mutex_t *avc_mutex;

  avc_mutex = dbus_new (pthread_mutex_t, 1);
  if (avc_mutex == NULL)
    {
      _dbus_warn ("Could not create mutex: %s\n", _dbus_strerror (errno));
      exit (1);
    }
  pthread_mutex_init (avc_mutex, NULL);

  return avc_mutex;
}

/* Acquire an AVC lock.  */
static void
avc_get_lock (void *lock)
{
  pthread_mutex_lock (lock);
}

/* Release an AVC lock.  */
static void
avc_release_lock (void *lock)
{
  pthread_mutex_unlock (lock);
}

/* Free an AVC lock.  */
static void
avc_free_lock (void *lock)
{
  pthread_mutex_destroy (lock);
  dbus_free (lock);
}
#endif /* HAVE_SELINUX */
246

247 248 249 250 251 252 253
/**
 * Return whether or not SELinux is enabled; must be
 * called after bus_selinux_init.
 */
dbus_bool_t
bus_selinux_enabled (void)
{
254
#ifdef HAVE_SELINUX
255
  return selinux_enabled;
256 257 258
#else
  return FALSE;
#endif /* HAVE_SELINUX */
259 260
}

261
/**
262
 * Do early initialization; determine whether SELinux is enabled.
263 264
 */
dbus_bool_t
265
bus_selinux_pre_init (void)
266 267
{
#ifdef HAVE_SELINUX
Colin Walters's avatar
Colin Walters committed
268
  int r;
269 270 271 272 273 274 275 276 277 278 279 280
  _dbus_assert (bus_sid == SECSID_WILD);
  
  /* Determine if we are running an SELinux kernel. */
  r = is_selinux_enabled ();
  if (r < 0)
    {
      _dbus_warn ("Could not tell if SELinux is enabled: %s\n",
                  _dbus_strerror (errno));
      return FALSE;
    }

  selinux_enabled = r != 0;
281 282 283 284 285 286 287
  return TRUE;
#else
  return TRUE;
#endif
}

/**
John Palmieri's avatar
John Palmieri committed
288
 * Initialize the user space access vector cache (AVC) for D-Bus and set up
289 290 291 292 293 294 295
 * logging callbacks.
 */
dbus_bool_t
bus_selinux_full_init (void)
{
#ifdef HAVE_SELINUX
  char *bus_context;
296

297 298
  _dbus_assert (bus_sid == SECSID_WILD);
  
299 300 301 302 303 304 305 306 307
  if (!selinux_enabled)
    {
      _dbus_verbose ("SELinux not enabled in this kernel.\n");
      return TRUE;
    }

  _dbus_verbose ("SELinux is enabled in this kernel.\n");

  avc_entry_ref_init (&aeref);
308
  if (avc_init ("avc", &mem_cb, &log_cb, &thread_cb, &lock_cb) < 0)
309 310 311 312 313 314 315 316 317 318
    {
      _dbus_warn ("Failed to start Access Vector Cache (AVC).\n");
      return FALSE;
    }
  else
    {
      openlog ("dbus", LOG_PERROR, LOG_USER);
      _dbus_verbose ("Access Vector Cache (AVC) started.\n");
    }

319 320 321 322 323 324 325 326 327
  if (avc_add_callback (policy_reload_callback, AVC_CALLBACK_RESET,
                       NULL, NULL, 0, 0) < 0)
    {
      _dbus_warn ("Failed to add policy reload callback: %s\n",
                  _dbus_strerror (errno));
      avc_destroy ();
      return FALSE;
    }

328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
  bus_context = NULL;
  bus_sid = SECSID_WILD;

  if (getcon (&bus_context) < 0)
    {
      _dbus_verbose ("Error getting context of bus: %s\n",
                     _dbus_strerror (errno));
      return FALSE;
    }
      
  if (avc_context_to_sid (bus_context, &bus_sid) < 0)
    {
      _dbus_verbose ("Error getting SID from bus context: %s\n",
                     _dbus_strerror (errno));
      freecon (bus_context);
      return FALSE;
    }

  freecon (bus_context);
  
348 349
  audit_init ();

350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
  return TRUE;
#else
  return TRUE;
#endif /* HAVE_SELINUX */
}

/**
 * Decrement SID reference count.
 * 
 * @param sid the SID to decrement
 */
void
bus_selinux_id_unref (BusSELinuxID *sid)
{
#ifdef HAVE_SELINUX
  if (!selinux_enabled)
    return;

  _dbus_assert (sid != NULL);
  
  sidput (SELINUX_SID_FROM_BUS (sid));
#endif /* HAVE_SELINUX */
}

void
bus_selinux_id_ref (BusSELinuxID *sid)
{
#ifdef HAVE_SELINUX
  if (!selinux_enabled)
    return;

  _dbus_assert (sid != NULL);
  
  sidget (SELINUX_SID_FROM_BUS (sid));
#endif /* HAVE_SELINUX */
}

/**
 * Determine if the SELinux security policy allows the given sender
 * security context to go to the given recipient security context.
 * This function determines if the requested permissions are to be
 * granted from the connection to the message bus or to another
 * optionally supplied security identifier (e.g. for a service
 * context).  Currently these permissions are either send_msg or
 * acquire_svc in the dbus class.
 *
 * @param sender_sid source security context
 * @param override_sid is the target security context.  If SECSID_WILD this will
 *        use the context of the bus itself (e.g. the default).
 * @param target_class is the target security class.
 * @param requested is the requested permissions.
 * @returns #TRUE if security policy allows the send.
 */
#ifdef HAVE_SELINUX
static dbus_bool_t
bus_selinux_check (BusSELinuxID        *sender_sid,
                   BusSELinuxID        *override_sid,
                   security_class_t     target_class,
408 409
                   access_vector_t      requested,
		   DBusString          *auxdata)
410 411 412
{
  if (!selinux_enabled)
    return TRUE;
413

414 415 416 417 418
  /* Make the security check.  AVC checks enforcing mode here as well. */
  if (avc_has_perm (SELINUX_SID_FROM_BUS (sender_sid),
                    override_sid ?
                    SELINUX_SID_FROM_BUS (override_sid) :
                    SELINUX_SID_FROM_BUS (bus_sid), 
419
                    target_class, requested, &aeref, auxdata) < 0)
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
    {
      _dbus_verbose ("SELinux denying due to security policy.\n");
      return FALSE;
    }
  else
    return TRUE;
}
#endif /* HAVE_SELINUX */

/**
 * Returns true if the given connection can acquire a service,
 * assuming the given security ID is needed for that service.
 *
 * @param connection connection that wants to own the service
 * @param service_sid the SID of the service from the table
 * @returns #TRUE if acquire is permitted.
 */
dbus_bool_t
bus_selinux_allows_acquire_service (DBusConnection     *connection,
439
                                    BusSELinuxID       *service_sid,
440 441
				    const char         *service_name,
				    DBusError          *error)
442 443 444
{
#ifdef HAVE_SELINUX
  BusSELinuxID *connection_sid;
445
  unsigned long spid;
446 447
  DBusString auxdata;
  dbus_bool_t ret;
448 449 450
  
  if (!selinux_enabled)
    return TRUE;
451
  
452
  connection_sid = bus_connection_get_selinux_id (connection);
453 454 455
  if (!dbus_connection_get_unix_process_id (connection, &spid))
    spid = 0;

456 457 458 459 460 461 462 463 464 465
  if (!_dbus_string_init (&auxdata))
    goto oom;
 
  if (!_dbus_string_append (&auxdata, "service="))
    goto oom;

  if (!_dbus_string_append (&auxdata, service_name))
    goto oom;

  if (spid)
466
    {
467 468 469 470 471
      if (!_dbus_string_append (&auxdata, " spid="))
	goto oom;

      if (!_dbus_string_append_uint (&auxdata, spid))
	goto oom;
472
    }
473
  
474 475 476 477 478 479 480 481 482 483 484 485 486 487
  ret = bus_selinux_check (connection_sid,
			   service_sid,
			   SECCLASS_DBUS,
			   DBUS__ACQUIRE_SVC,
			   &auxdata);

  _dbus_string_free (&auxdata);
  return ret;

 oom:
  _dbus_string_free (&auxdata);
  BUS_SET_OOM (error);
  return FALSE;

488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
#else
  return TRUE;
#endif /* HAVE_SELINUX */
}

/**
 * Check if SELinux security controls allow the message to be sent to a
 * particular connection based on the security context of the sender and
 * that of the receiver. The destination connection need not be the
 * addressed recipient, it could be an "eavesdropper"
 *
 * @param sender the sender of the message.
 * @param proposed_recipient the connection the message is to be sent to.
 * @returns whether to allow the send
 */
dbus_bool_t
bus_selinux_allows_send (DBusConnection     *sender,
505 506 507 508 509
                         DBusConnection     *proposed_recipient,
			 const char         *msgtype,
			 const char         *interface,
			 const char         *member,
			 const char         *error_name,
510 511
			 const char         *destination,
			 DBusError          *error)
512 513 514 515
{
#ifdef HAVE_SELINUX
  BusSELinuxID *recipient_sid;
  BusSELinuxID *sender_sid;
516
  unsigned long spid, tpid;
517 518
  DBusString auxdata;
  dbus_bool_t ret;
519
  dbus_bool_t string_alloced;
520 521 522 523

  if (!selinux_enabled)
    return TRUE;

524
  if (!sender || !dbus_connection_get_unix_process_id (sender, &spid))
525
    spid = 0;
526
  if (!proposed_recipient || !dbus_connection_get_unix_process_id (proposed_recipient, &tpid))
527 528
    tpid = 0;

529
  string_alloced = FALSE;
530 531
  if (!_dbus_string_init (&auxdata))
    goto oom;
532
  string_alloced = TRUE;
533 534 535 536 537 538 539 540

  if (!_dbus_string_append (&auxdata, "msgtype="))
    goto oom;

  if (!_dbus_string_append (&auxdata, msgtype))
    goto oom;

  if (interface)
541
    {
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
      if (!_dbus_string_append (&auxdata, " interface="))
	goto oom;
      if (!_dbus_string_append (&auxdata, interface))
	goto oom;
    }

  if (member)
    {
      if (!_dbus_string_append (&auxdata, " member="))
	goto oom;
      if (!_dbus_string_append (&auxdata, member))
	goto oom;
    }

  if (error_name)
    {
      if (!_dbus_string_append (&auxdata, " error_name="))
	goto oom;
      if (!_dbus_string_append (&auxdata, error_name))
	goto oom;
    }

  if (destination)
    {
      if (!_dbus_string_append (&auxdata, " dest="))
	goto oom;
      if (!_dbus_string_append (&auxdata, destination))
	goto oom;
    }

  if (spid)
    {
      if (!_dbus_string_append (&auxdata, " spid="))
	goto oom;

      if (!_dbus_string_append_uint (&auxdata, spid))
	goto oom;
    }

  if (tpid)
    {
      if (!_dbus_string_append (&auxdata, " tpid="))
	goto oom;

      if (!_dbus_string_append_uint (&auxdata, tpid))
	goto oom;
588 589
    }

590 591 592 593 594 595 596
  sender_sid = bus_connection_get_selinux_id (sender);
  /* A NULL proposed_recipient means the bus itself. */
  if (proposed_recipient)
    recipient_sid = bus_connection_get_selinux_id (proposed_recipient);
  else
    recipient_sid = BUS_SID_FROM_SELINUX (bus_sid);

597 598 599 600 601 602 603 604 605 606 607
  ret = bus_selinux_check (sender_sid, 
			   recipient_sid,
			   SECCLASS_DBUS, 
			   DBUS__SEND_MSG,
			   &auxdata);

  _dbus_string_free (&auxdata);

  return ret;

 oom:
608 609
  if (string_alloced)
    _dbus_string_free (&auxdata);
610 611 612
  BUS_SET_OOM (error);
  return FALSE;
  
613 614 615 616 617
#else
  return TRUE;
#endif /* HAVE_SELINUX */
}

618 619
dbus_bool_t
bus_selinux_append_context (DBusMessage    *message,
620 621
			    BusSELinuxID   *sid,
			    DBusError      *error)
622
{
623
#ifdef HAVE_SELINUX
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
  char *context;

  if (avc_sid_to_context (SELINUX_SID_FROM_BUS (sid), &context) < 0)
    {
      if (errno == ENOMEM)
        BUS_SET_OOM (error);
      else
        dbus_set_error (error, DBUS_ERROR_FAILED,
                        "Error getting context from SID: %s\n",
			_dbus_strerror (errno));
      return FALSE;
    }
  if (!dbus_message_append_args (message,
				 DBUS_TYPE_ARRAY,
				 DBUS_TYPE_BYTE,
				 &context,
				 strlen (context),
				 DBUS_TYPE_INVALID))
    {
      _DBUS_SET_OOM (error);
      return FALSE;
    }
  freecon (context);
  return TRUE;
648
#else
649
  return TRUE;
650
#endif
651 652
}

653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
/**
 * Gets the security context of a connection to the bus. It is up to
 * the caller to freecon() when they are done. 
 *
 * @param connection the connection to get the context of.
 * @param con the location to store the security context.
 * @returns #TRUE if context is successfully obtained.
 */
#ifdef HAVE_SELINUX
static dbus_bool_t
bus_connection_read_selinux_context (DBusConnection     *connection,
                                     char              **con)
{
  int fd;

  if (!selinux_enabled)
    return FALSE;

  _dbus_assert (connection != NULL);
  
  if (!dbus_connection_get_unix_fd (connection, &fd))
    {
      _dbus_verbose ("Failed to get file descriptor of socket.\n");
      return FALSE;
    }
  
  if (getpeercon (fd, con) < 0)
    {
      _dbus_verbose ("Error getting context of socket peer: %s\n",
                     _dbus_strerror (errno));
      return FALSE;
    }
  
  _dbus_verbose ("Successfully read connection context.\n");
  return TRUE;
}
#endif /* HAVE_SELINUX */

/**
 * Read the SELinux ID from the connection.
 *
 * @param connection the connection to read from
 * @returns the SID if successfully determined, #NULL otherwise.
 */
BusSELinuxID*
bus_selinux_init_connection_id (DBusConnection *connection,
                                DBusError      *error)
{
#ifdef HAVE_SELINUX
  char *con;
  security_id_t sid;
  
  if (!selinux_enabled)
    return NULL;

  if (!bus_connection_read_selinux_context (connection, &con))
    {
      dbus_set_error (error, DBUS_ERROR_FAILED,
                      "Failed to read an SELinux context from connection");
      _dbus_verbose ("Error getting peer context.\n");
      return NULL;
    }

  _dbus_verbose ("Converting context to SID to store on connection\n");

  if (avc_context_to_sid (con, &sid) < 0)
    {
      if (errno == ENOMEM)
        BUS_SET_OOM (error);
      else
        dbus_set_error (error, DBUS_ERROR_FAILED,
724 725
                        "Error getting SID from context \"%s\": %s\n",
			con, _dbus_strerror (errno));
726
      
727 728
      _dbus_warn ("Error getting SID from context \"%s\": %s\n",
		  con, _dbus_strerror (errno));
729 730 731 732 733 734 735 736 737 738 739 740 741
      
      freecon (con);
      return NULL;
    }
 
  freecon (con); 
  return BUS_SID_FROM_SELINUX (sid);
#else
  return NULL;
#endif /* HAVE_SELINUX */
}


742 743
/**
 * Function for freeing hash table data.  These SIDs
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
 * should no longer be referenced.
 */
static void
bus_selinux_id_table_free_value (BusSELinuxID *sid)
{
#ifdef HAVE_SELINUX
  /* NULL sometimes due to how DBusHashTable works */
  if (sid)
    bus_selinux_id_unref (sid);
#endif /* HAVE_SELINUX */
}

/**
 * Creates a new table mapping service names to security ID.
 * A security ID is a "compiled" security context, a security
 * context is just a string.
 *
 * @returns the new table or #NULL if no memory
 */
DBusHashTable*
bus_selinux_id_table_new (void)
{
  return _dbus_hash_table_new (DBUS_HASH_STRING,
                               (DBusFreeFunction) dbus_free,
                               (DBusFreeFunction) bus_selinux_id_table_free_value);
}

/** 
 * Hashes a service name and service context into the service SID
 * table as a string and a SID.
 *
 * @param service_name is the name of the service.
 * @param service_context is the context of the service.
 * @param service_table is the table to hash them into.
 * @return #FALSE if not enough memory
 */
dbus_bool_t
bus_selinux_id_table_insert (DBusHashTable *service_table,
                             const char    *service_name,
                             const char    *service_context)
{
#ifdef HAVE_SELINUX
  dbus_bool_t retval;
  security_id_t sid;
  char *key;

  if (!selinux_enabled)
    return TRUE;

  sid = SECSID_WILD;
  retval = FALSE;

  key = _dbus_strdup (service_name);
  if (key == NULL)
    return retval;
  
800
  if (avc_context_to_sid ((char *) service_context, &sid) < 0)
801
    {
802
      if (errno == ENOMEM)
803 804 805 806 807
        {
	  dbus_free (key);
          return FALSE;
	}

808 809 810
      _dbus_warn ("Error getting SID from context \"%s\": %s\n",
		  (char *) service_context,
                  _dbus_strerror (errno));
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
      goto out;
    }

  if (!_dbus_hash_table_insert_string (service_table,
                                       key,
                                       BUS_SID_FROM_SELINUX (sid)))
    goto out;

  _dbus_verbose ("Parsed \tservice: %s \n\t\tcontext: %s\n",
                  key, 
                  sid->ctx);

  /* These are owned by the hash, so clear them to avoid unref */
  key = NULL;
  sid = SECSID_WILD;

  retval = TRUE;
  
 out:
  if (sid != SECSID_WILD)
    sidput (sid);

  if (key)
    dbus_free (key);

  return retval;
#else
  return TRUE;
#endif /* HAVE_SELINUX */
}


/**
 * Find the security identifier associated with a particular service
 * name.  Return a pointer to this SID, or #NULL/SECSID_WILD if the
 * service is not found in the hash table.  This should be nearly a
 * constant time operation.  If SELinux support is not available,
 * always return NULL.
 *
 * @param service_table the hash table to check for service name.
 * @param service_name the name of the service to look for.
 * @returns the SELinux ID associated with the service
 */
BusSELinuxID*
bus_selinux_id_table_lookup (DBusHashTable    *service_table,
                             const DBusString *service_name)
{
#ifdef HAVE_SELINUX
  security_id_t sid;

  sid = SECSID_WILD;     /* default context */

  if (!selinux_enabled)
    return NULL;
  
  _dbus_verbose ("Looking up service SID for %s\n",
                 _dbus_string_get_const_data (service_name));

  sid = _dbus_hash_table_lookup_string (service_table,
                                        _dbus_string_get_const_data (service_name));

  if (sid == SECSID_WILD)
    _dbus_verbose ("Service %s not found\n", 
                   _dbus_string_get_const_data (service_name));
  else
    _dbus_verbose ("Service %s found\n", 
                   _dbus_string_get_const_data (service_name));

  return BUS_SID_FROM_SELINUX (sid);
#endif /* HAVE_SELINUX */
  return NULL;
}

884
/**
John Palmieri's avatar
John Palmieri committed
885
 * Get the SELinux policy root.  This is used to find the D-Bus
886 887 888 889 890 891 892 893 894 895 896 897
 * specific config file within the policy.
 */
const char *
bus_selinux_get_policy_root (void)
{
#ifdef HAVE_SELINUX
  return selinux_policy_root ();
#else
  return NULL;
#endif /* HAVE_SELINUX */
} 

898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
/**
 * For debugging:  Print out the current hash table of service SIDs.
 */
void
bus_selinux_id_table_print (DBusHashTable *service_table)
{
#ifdef DBUS_ENABLE_VERBOSE_MODE
#ifdef HAVE_SELINUX
  DBusHashIter iter;

  if (!selinux_enabled)
    return;
  
  _dbus_verbose ("Service SID Table:\n");
  _dbus_hash_iter_init (service_table, &iter);
  while (_dbus_hash_iter_next (&iter))
    {
      const char *key = _dbus_hash_iter_get_string_key (&iter);
      security_id_t sid = _dbus_hash_iter_get_value (&iter);
      _dbus_verbose ("The key is %s\n", key);
      _dbus_verbose ("The context is %s\n", sid->ctx);
      _dbus_verbose ("The refcount is %d\n", sid->refcnt);
    }
#endif /* HAVE_SELINUX */
#endif /* DBUS_ENABLE_VERBOSE_MODE */
}


#ifdef DBUS_ENABLE_VERBOSE_MODE
#ifdef HAVE_SELINUX
/**
 * Print out some AVC statistics.
 */
static void
bus_avc_print_stats (void)
{
  struct avc_cache_stats cstats;

  if (!selinux_enabled)
    return;
  
  _dbus_verbose ("AVC Statistics:\n");
  avc_cache_stats (&cstats);
  avc_av_stats ();
  _dbus_verbose ("AVC Cache Statistics:\n");
  _dbus_verbose ("Entry lookups: %d\n", cstats.entry_lookups);
  _dbus_verbose ("Entry hits: %d\n", cstats.entry_hits);
  _dbus_verbose ("Entry misses %d\n", cstats.entry_misses);
  _dbus_verbose ("Entry discards: %d\n", cstats.entry_discards);
  _dbus_verbose ("CAV lookups: %d\n", cstats.cav_lookups);
  _dbus_verbose ("CAV hits: %d\n", cstats.cav_hits);
  _dbus_verbose ("CAV probes: %d\n", cstats.cav_probes);
  _dbus_verbose ("CAV misses: %d\n", cstats.cav_misses);
}
#endif /* HAVE_SELINUX */
#endif /* DBUS_ENABLE_VERBOSE_MODE */


/**
 * Destroy the AVC before we terminate.
 */
void
bus_selinux_shutdown (void)
{
#ifdef HAVE_SELINUX
  if (!selinux_enabled)
    return;

966 967 968 969 970 971
  _dbus_verbose ("AVC shutdown\n");

  if (bus_sid != SECSID_WILD)
    {
      sidput (bus_sid);
      bus_sid = SECSID_WILD;
972

973
#ifdef DBUS_ENABLE_VERBOSE_MODE
974 975 976 977
 
      if (_dbus_is_verbose()) 
        bus_avc_print_stats ();
 
978 979
#endif /* DBUS_ENABLE_VERBOSE_MODE */

980
      avc_destroy ();
981 982 983
#ifdef HAVE_LIBAUDIT
      audit_close (audit_fd);
#endif /* HAVE_LIBAUDIT */
984
    }
985 986 987
#endif /* HAVE_SELINUX */
}