OpenVAS Libraries  9.0.3
drop_privileges.c
Go to the documentation of this file.
1 /* openvas-libraries/base
2  * $Id$
3  * Description: Privilege dropping.
4  *
5  * Authors:
6  * Felix Wolfsteller <felix.wolfsteller@intevation.de>
7  * based on work by Michael Wiegand <michael.wiegand@intevation.de>
8  *
9  * Copyright:
10  * Copyright (C) 2010 Greenbone Networks GmbH
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License
14  * as published by the Free Software Foundation; either version 2
15  * of the License, or (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
25  */
26 
37 #include "drop_privileges.h"
38 
39 #include <pwd.h>
40 #include <unistd.h>
41 #include <sys/types.h>
42 #include <grp.h>
43 
54 static gint
55 drop_privileges_error (GError ** error, gint errorcode, const gchar * message)
56 {
57  g_set_error (error, OPENVAS_DROP_PRIVILEGES, errorcode, "%s", message);
58  return errorcode;
59 }
60 
61 
78 int
79 drop_privileges (gchar * username, GError ** error)
80 {
81  struct passwd *user_pw = NULL;
82 
83  g_return_val_if_fail (*error == NULL,
85 
86  if (username == NULL)
87  username = "nobody";
88 
89  if (geteuid () == 0)
90  {
91  if ((user_pw = getpwnam (username)))
92  {
93  if (initgroups (username, user_pw->pw_gid) != 0)
94  return drop_privileges_error
95  (error,
97  "Failed to drop supplementary groups privileges!\n");
98  if (setgid (user_pw->pw_gid) != 0)
99  return drop_privileges_error
100  (error,
102  "Failed to drop group privileges!\n");
103  if (setuid (user_pw->pw_uid) != 0)
104  return drop_privileges_error
105  (error,
107  "Failed to drop user privileges!\n");
108  }
109  else
110  {
111  g_set_error (error, OPENVAS_DROP_PRIVILEGES,
113  "Failed to get gid and uid for user %s.", username);
115  }
117  }
118  else
119  {
120  return drop_privileges_error (error,
122  "Only root can drop its privileges.");
123  }
124 }
#define OPENVAS_DROP_PRIVILEGES_FAIL_NOT_ROOT
#define OPENVAS_DROP_PRIVILEGES_ERROR_ALREADY_SET
#define OPENVAS_DROP_PRIVILEGES_FAIL_DROP_UID
int drop_privileges(gchar *username, GError **error)
Naive attempt to drop privileges.
#define OPENVAS_DROP_PRIVILEGES_FAIL_DROP_GID
#define OPENVAS_DROP_PRIVILEGES_FAIL_SUPPLEMENTARY
#define OPENVAS_DROP_PRIVILEGES_OK
#define OPENVAS_DROP_PRIVILEGES_FAIL_UNKNOWN_USER
#define OPENVAS_DROP_PRIVILEGES
The GQuark for privilege dropping errors.