selinux.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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/flask.h>
  25. #include <selinux/context.h>
  26. #include "compat.h"
  27. int
  28. setexecfilecon(const char *filename, const char *fallback)
  29. {
  30. int rc;
  31. security_context_t curcon = NULL, newcon = NULL, filecon = NULL;
  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. rc = security_compute_create(curcon, filecon, SECCLASS_PROCESS, &newcon);
  42. if (rc < 0)
  43. goto out;
  44. if (strcmp(curcon, newcon) == 0) {
  45. /* No default transition, use fallback for now. */
  46. rc = -1;
  47. tmpcon = context_new(curcon);
  48. if (tmpcon == NULL)
  49. goto out;
  50. if (context_type_set(tmpcon, fallback))
  51. goto out;
  52. freecon(newcon);
  53. newcon = strdup(context_str(tmpcon));
  54. if (newcon == NULL)
  55. goto out;
  56. }
  57. rc = setexeccon(newcon);
  58. out:
  59. if (rc < 0 && security_getenforce() == 0)
  60. rc = 0;
  61. context_free(tmpcon);
  62. freecon(newcon);
  63. freecon(curcon);
  64. freecon(filecon);
  65. return rc;
  66. }