Add a function to drop privileges.
authorPierre Habouzit <madcoder@debian.org>
Thu, 30 Aug 2007 21:59:57 +0000 (23:59 +0200)
committerPierre Habouzit <madcoder@debian.org>
Thu, 30 Aug 2007 21:59:57 +0000 (23:59 +0200)
daemon.c
daemon.h

index 392dccb..1c74ed3 100644 (file)
--- a/daemon.c
+++ b/daemon.c
  * Copyright © 2007 Pierre Habouzit
  */
 
-#include <sys/un.h>
 #include <fcntl.h>
+#include <grp.h>
+#include <pwd.h>
+#include <sys/un.h>
 
 #include "common.h"
 #include "daemon.h"
@@ -149,3 +151,28 @@ int daemon_detach(void)
     setsid();
     return 0;
 }
+
+int drop_privilegies(const char *user, const char *group)
+{
+    if (!geteuid()) {
+        struct passwd *pw;
+        struct group *gr;
+
+        if (group) {
+            gr = getgrnam(group);
+            if (!gr)
+                return -1;
+            setgid(gr->gr_gid);
+        }
+
+        pw = getpwnam(user);
+        if (!pw)
+            return -1;
+        if (!group) {
+            setgid(pw->pw_gid);
+        }
+        setuid(pw->pw_uid);
+    }
+
+    return 0;
+}
index e1b458f..5bc2cfb 100644 (file)
--- a/daemon.h
+++ b/daemon.h
@@ -40,5 +40,6 @@ int tcp_listen_nonblock(const struct sockaddr *addr, socklen_t len);
 int accept_nonblock(int fd);
 
 int daemon_detach(void);
+int drop_privilegies(const char *user, const char *group);
 
 #endif