secure_getenv.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /* Look up an environment variable, returning NULL in insecure situations.
  2. Copyright 2013-2017 Free Software Foundation, Inc.
  3. This program is free software: you can redistribute it and/or modify it
  4. under the terms of the GNU Lesser General Public License as published
  5. by the Free Software Foundation; either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  13. #include <config.h>
  14. #include <stdlib.h>
  15. #if !HAVE___SECURE_GETENV
  16. # if HAVE_ISSETUGID || (HAVE_GETUID && HAVE_GETEUID && HAVE_GETGID && HAVE_GETEGID)
  17. # include <unistd.h>
  18. # endif
  19. #endif
  20. char *
  21. secure_getenv (char const *name)
  22. {
  23. #if HAVE___SECURE_GETENV /* glibc */
  24. return __secure_getenv (name);
  25. #elif HAVE_ISSETUGID /* OS X, FreeBSD, NetBSD, OpenBSD */
  26. if (issetugid ())
  27. return NULL;
  28. return getenv (name);
  29. #elif HAVE_GETUID && HAVE_GETEUID && HAVE_GETGID && HAVE_GETEGID /* other Unix */
  30. if (geteuid () != getuid () || getegid () != getgid ())
  31. return NULL;
  32. return getenv (name);
  33. #elif (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__ /* native Windows */
  34. /* On native Windows, there is no such concept as setuid or setgid binaries.
  35. - Programs launched as system services have high privileges, but they don't
  36. inherit environment variables from a user.
  37. - Programs launched by a user with "Run as Administrator" have high
  38. privileges and use the environment variables, but the user has been asked
  39. whether he agrees.
  40. - Programs launched by a user without "Run as Administrator" cannot gain
  41. high privileges, therefore there is no risk. */
  42. return getenv (name);
  43. #else
  44. return NULL;
  45. #endif
  46. }