From a733e4c62c019ab4cb659c705d22a391a58becee Mon Sep 17 00:00:00 2001
From: "Leigh B. Stoller" <stoller@flux.utah.edu>
Date: Tue, 23 Dec 2003 14:34:09 +0000
Subject: [PATCH] Change to run as nobody/nobody when started as root.

---
 sensors/slothd/sdcollectd.c | 33 +++++++++++++++++++++++++++++++++
 sensors/slothd/sdcollectd.h |  3 +++
 2 files changed, 36 insertions(+)

diff --git a/sensors/slothd/sdcollectd.c b/sensors/slothd/sdcollectd.c
index 038797cb93..e0acf7d7d3 100644
--- a/sensors/slothd/sdcollectd.c
+++ b/sensors/slothd/sdcollectd.c
@@ -123,6 +123,39 @@ int main(int argc, char **argv) {
     info(build_info);
   }
 
+  /*
+   * Change to non-root user!
+   */
+  if (geteuid() == 0) {
+    struct passwd	*pw;
+    uid_t		uid;
+    gid_t		gid;
+
+    /*
+     * Must be a valid user of course.
+     */
+    if ((pw = getpwnam(RUNASUSER)) == NULL) {
+      error("invalid user: %s", RUNASUSER);
+      exit(1);
+    }
+    uid = pw->pw_uid;
+    gid = pw->pw_gid;
+
+    if (setgroups(1, &gid)) {
+      errorc("setgroups");
+      exit(1);
+    }
+    if (setgid(gid)) {
+      errorc("setgid");
+      exit(1);
+    }
+    if (setuid(uid)) {
+      errorc("setuid");
+      exit(1);
+    }
+    info("Flipped to user/group %d/%d\n", uid, gid);
+  }
+
   /* do our thing - just loop collecting data from clients, and insert into
      DB. 
   */
diff --git a/sensors/slothd/sdcollectd.h b/sensors/slothd/sdcollectd.h
index db512f0988..7a7b38951a 100644
--- a/sensors/slothd/sdcollectd.h
+++ b/sensors/slothd/sdcollectd.h
@@ -23,6 +23,8 @@
 #include <errno.h>
 #include <signal.h>
 #include <syslog.h>
+#include <pwd.h>
+#include <grp.h>
 #include <tbdb.h>
 #include "log.h"
 
@@ -32,6 +34,7 @@
 #define BUFSIZE 1500
 #define MAXNUMIFACES 10
 #define MACADDRLEN 12
+#define RUNASUSER "nobody"
 
 #define NUMACTTYPES 4
 #define ACTSTRARRAY {"last_tty_act", "last_cpu_act", "last_net_act", "last_ext_act"}
-- 
GitLab