change_user.cc 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. // $Id$
  15. #include <errno.h>
  16. #include <string.h>
  17. #include <pwd.h>
  18. #include <unistd.h>
  19. #include <boost/lexical_cast.hpp>
  20. #include <exceptions/exceptions.h>
  21. #include <auth/common.h>
  22. using namespace boost;
  23. using namespace std;
  24. void
  25. changeUser(const char* const username) {
  26. const struct passwd *runas_pw = NULL;
  27. runas_pw = getpwnam(username);
  28. endpwent();
  29. if (runas_pw == NULL) {
  30. try {
  31. runas_pw = getpwuid(lexical_cast<uid_t>(username));
  32. endpwent();
  33. } catch (const bad_lexical_cast&) {
  34. ; // fall through to isc_throw below.
  35. }
  36. }
  37. if (runas_pw == NULL) {
  38. throw FatalError("Unknown user name or UID:" + string(username));
  39. }
  40. if (setgid(runas_pw->pw_gid) < 0) {
  41. throw FatalError("setgid() failed: " + string(strerror(errno)));
  42. }
  43. if (setuid(runas_pw->pw_uid) < 0) {
  44. throw FatalError("setuid() failed: " + string(strerror(errno)));
  45. }
  46. }