change_user.cc 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Copyright (C) 2010 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <errno.h>
  15. #include <string.h>
  16. #include <pwd.h>
  17. #include <unistd.h>
  18. #include <boost/lexical_cast.hpp>
  19. #include <exceptions/exceptions.h>
  20. #include <auth/common.h>
  21. using namespace boost;
  22. using namespace std;
  23. void
  24. changeUser(const char* const username) {
  25. const struct passwd *runas_pw = NULL;
  26. runas_pw = getpwnam(username);
  27. endpwent();
  28. if (runas_pw == NULL) {
  29. try {
  30. runas_pw = getpwuid(lexical_cast<uid_t>(username));
  31. endpwent();
  32. } catch (const bad_lexical_cast&) {
  33. ; // fall through to isc_throw below.
  34. }
  35. }
  36. if (runas_pw == NULL) {
  37. throw FatalError("Unknown user name or UID:" + string(username));
  38. }
  39. if (setgid(runas_pw->pw_gid) < 0) {
  40. throw FatalError("setgid() failed: " + string(strerror(errno)));
  41. }
  42. if (setuid(runas_pw->pw_uid) < 0) {
  43. throw FatalError("setuid() failed: " + string(strerror(errno)));
  44. }
  45. }