From 12ebf48b0e549e1080cf104e1f2ca29002a18336 Mon Sep 17 00:00:00 2001 From: Gunnar Beutner Date: Sun, 15 Sep 2013 10:28:54 +0200 Subject: [PATCH] Implement setgid/setuid support. Fixes #3841 --- etc/init.d/icinga2.in | 4 +++- icinga-app/icinga.cpp | 48 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/etc/init.d/icinga2.in b/etc/init.d/icinga2.in index 8f2d40018..15054619e 100644 --- a/etc/init.d/icinga2.in +++ b/etc/init.d/icinga2.in @@ -24,6 +24,8 @@ DAEMON=$bindir/icinga2 ICINGA2_CONFIG_FILE=$sysconfdir/icinga2/icinga2.conf ICINGA2_PID_FILE=$localstatedir/run/icinga2/icinga2.pid ICINGA2_ERROR_LOG=$localstatedir/log/icinga2/error.log +ICINGA2_USER=icinga +ICINGA2_GROUP=icinga test -x $DAEMON || exit 0 @@ -49,7 +51,7 @@ start() { fi printf "Starting Icinga 2: " - $DAEMON -c $ICINGA2_CONFIG_FILE -d -e $ICINGA2_ERROR_LOG + $DAEMON -c $ICINGA2_CONFIG_FILE -d -e $ICINGA2_ERROR_LOG -u $ICINGA2_USER -g $ICINGA2_GROUP echo "Done" echo diff --git a/icinga-app/icinga.cpp b/icinga-app/icinga.cpp index 857c9b04c..734a19d93 100644 --- a/icinga-app/icinga.cpp +++ b/icinga-app/icinga.cpp @@ -24,6 +24,7 @@ #include "base/logger_fwd.h" #include "base/timer.h" #include "base/utility.h" +#include "base/exception.h" #include #include #include @@ -34,6 +35,9 @@ # define ICINGA_VERSION VERSION ", " GIT_MESSAGE # include +# include +# include +# include #endif /* _WIN32 */ using namespace icinga; @@ -227,6 +231,10 @@ int main(int argc, char **argv) ("debug,x", "enable debugging") ("daemonize,d", "detach from the controlling terminal") ("errorlog,e", po::value(), "log fatal errors to the specified log file (only works in combination with --daemonize)") +#ifndef _WIN32 + ("user,u", po::value(), "user to run Icinga as") + ("group,g", po::value(), "group to run Icinga as") +#endif ; try { @@ -240,6 +248,46 @@ int main(int argc, char **argv) po::notify(g_AppParams); +#ifndef _WIN32 + if (g_AppParams.count("user")) { + String user = g_AppParams["user"].as(); + + errno = 0; + struct passwd *pw = getpwnam(user.CStr()); + + if (!pw) { + BOOST_THROW_EXCEPTION(posix_error() + << boost::errinfo_api_function("getpwnam") + << boost::errinfo_errno(errno)); + } + + if (setuid(pw->pw_uid) < 0) { + BOOST_THROW_EXCEPTION(posix_error() + << boost::errinfo_api_function("setuid") + << boost::errinfo_errno(errno)); + } + } + + if (g_AppParams.count("group")) { + String group = g_AppParams["group"].as(); + + errno = 0; + struct group *gr = getgrnam(group.CStr()); + + if (!gr) { + BOOST_THROW_EXCEPTION(posix_error() + << boost::errinfo_api_function("getpwnam") + << boost::errinfo_errno(errno)); + } + + if (setgid(gr->gr_gid) < 0) { + BOOST_THROW_EXCEPTION(posix_error() + << boost::errinfo_api_function("setgid") + << boost::errinfo_errno(errno)); + } + } +#endif /* _WIN32 */ + if (g_AppParams.count("debug")) Application::SetDebugging(true); -- 2.40.0