From 528da250ae0f97514144573d52920595abdc02e0 Mon Sep 17 00:00:00 2001
From: Alexander Barton <alex@barton.de>
Date: Tue, 18 Sep 2012 12:16:05 +0200
Subject: [PATCH] Don't run if changing user ID fails

But initialize the default UID to the current user, so that the logic
is as following:

 1. Set default configured UID to the current user
 2. Read UID from configuration ("ServerUID"), if any
 3. Change configured UID to "nobody" if it is "root" (0)
 4. Set the configured UID and exit on error
 5. Run as a) current user, b) configured user, c) nobody,
    but _never_run as root.

Reported by Federico G. Schwindt, thanks!
---
 src/ngircd/conf.c   |    3 ++-
 src/ngircd/ngircd.c |   10 +++-------
 2 files changed, 5 insertions(+), 8 deletions(-)

diff --git a/src/ngircd/conf.c b/src/ngircd/conf.c
index 5853926..87f4d11 100644
--- a/src/ngircd/conf.c
+++ b/src/ngircd/conf.c
@@ -694,7 +694,8 @@ Set_Defaults(bool InitServers)
 	strlcat(Conf_MotdFile, MOTD_FILE, sizeof(Conf_MotdFile));
 	strcpy(Conf_ServerPwd, "");
 	strlcpy(Conf_PidFile, PID_FILE, sizeof(Conf_PidFile));
-	Conf_UID = Conf_GID = 0;
+	Conf_UID = geteuid();
+	Conf_GID = getegid();
 
 	/* Limits */
 	Conf_ConnectRetry = 60;
diff --git a/src/ngircd/ngircd.c b/src/ngircd/ngircd.c
index 585e2ac..867392d 100644
--- a/src/ngircd/ngircd.c
+++ b/src/ngircd/ngircd.c
@@ -645,7 +645,7 @@ NGIRCd_Init(bool NGIRCd_NoDaemon)
 	bool chrooted = false;
 	struct passwd *pwd;
 	struct group *grp;
-	int real_errno, fd = -1;
+	int fd = -1;
 	pid_t pid;
 
 	if (initialized)
@@ -702,26 +702,22 @@ NGIRCd_Init(bool NGIRCd_NoDaemon)
 	/* Change group ID */
 	if (getgid() != Conf_GID) {
 		if (setgid(Conf_GID) != 0) {
-			real_errno = errno;
 			grp = getgrgid(Conf_GID);
 			Log(LOG_ERR, "Can't change group ID to %s(%u): %s",
 			    grp ? grp->gr_name : "?", Conf_GID,
 			    strerror(errno));
-			if (real_errno != EPERM) 
-				goto out;
+			goto out;
 		}
 	}
 
 	/* Change user ID */
 	if (getuid() != Conf_UID) {
 		if (setuid(Conf_UID) != 0) {
-			real_errno = errno;
 			pwd = getpwuid(Conf_UID);
 			Log(LOG_ERR, "Can't change user ID to %s(%u): %s",
 			    pwd ? pwd->pw_name : "?", Conf_UID,
 			    strerror(errno));
-			if (real_errno != EPERM)
-				goto out;
+			goto out;
 		}
 	}
 
-- 
1.7.10

