selinux.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * libcompat - system compatibility library
  3. *
  4. * Based on code from libselinux, Public Domain.
  5. * Copyright © 2014 Guillem Jover <guillem@debian.org>
  6. *
  7. * This is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  19. */
  20. #include <config.h>
  21. #include <string.h>
  22. #include <stdlib.h>
  23. #include <selinux/selinux.h>
  24. #include <selinux/context.h>
  25. #include "compat.h"
  26. int
  27. setexecfilecon(const char *filename, const char *fallback)
  28. {
  29. int rc;
  30. security_context_t curcon = NULL, newcon = NULL, filecon = NULL;
  31. security_class_t seclass;
  32. context_t tmpcon = NULL;
  33. if (is_selinux_enabled() < 1)
  34. return 0;
  35. rc = getcon(&curcon);
  36. if (rc < 0)
  37. goto out;
  38. rc = getfilecon(filename, &filecon);
  39. if (rc < 0)
  40. goto out;
  41. seclass = string_to_security_class("process");
  42. if (seclass == 0)
  43. goto out;
  44. rc = security_compute_create(curcon, filecon, seclass, &newcon);
  45. if (rc < 0)
  46. goto out;
  47. if (strcmp(curcon, newcon) == 0) {
  48. /* No default transition, use fallback for now. */
  49. rc = -1;
  50. tmpcon = context_new(curcon);
  51. if (tmpcon == NULL)
  52. goto out;
  53. if (context_type_set(tmpcon, fallback))
  54. goto out;
  55. freecon(newcon);
  56. newcon = strdup(context_str(tmpcon));
  57. if (newcon == NULL)
  58. goto out;
  59. }
  60. rc = setexeccon(newcon);
  61. out:
  62. if (rc < 0 && security_getenforce() == 0)
  63. rc = 0;
  64. context_free(tmpcon);
  65. freecon(newcon);
  66. freecon(curcon);
  67. freecon(filecon);
  68. return rc;
  69. }