Greenbone Vulnerability Management Libraries 22.32.0
drop_privileges.c
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2010-2023 Greenbone AG
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later
4 */
5
10
11#include "drop_privileges.h"
12
13#include <grp.h> /* for initgroups */
14#include <pwd.h> /* for passwd, getpwnam */
15#include <sys/types.h>
16#include <unistd.h> /* for geteuid, setgid, setuid */
17
18#undef G_LOG_DOMAIN
22#define G_LOG_DOMAIN "libgvm base"
23
34static gint
35drop_privileges_error (GError **error, gint errorcode, const gchar *message)
36{
37 g_set_error (error, GVM_DROP_PRIVILEGES, errorcode, "%s", message);
38 return errorcode;
39}
40
57int
58drop_privileges (gchar *username, GError **error)
59{
60 g_return_val_if_fail (*error == NULL, GVM_DROP_PRIVILEGES_ERROR_ALREADY_SET);
61
62 if (username == NULL)
63 username = "nobody";
64
65 if (geteuid () == 0)
66 {
67 struct passwd *user_pw;
68
69 user_pw = getpwnam (username);
70 if (user_pw)
71 {
72 if (initgroups (username, user_pw->pw_gid) != 0)
75 "Failed to drop supplementary groups privileges!\n");
76 if (setgid (user_pw->pw_gid) != 0)
77 return drop_privileges_error (error,
79 "Failed to drop group privileges!\n");
80 if (setuid (user_pw->pw_uid) != 0)
81 return drop_privileges_error (error,
83 "Failed to drop user privileges!\n");
84 }
85 else
86 {
87 g_set_error (error, GVM_DROP_PRIVILEGES,
89 "Failed to get gid and uid for user %s.", username);
91 }
93 }
94 else
95 {
97 "Only root can drop its privileges.");
98 }
99}
static gint drop_privileges_error(GError **error, gint errorcode, const gchar *message)
Sets an error and return errorcode.
int drop_privileges(gchar *username, GError **error)
Drop privileges.
Privilege dropping header file.
#define GVM_DROP_PRIVILEGES_FAIL_DROP_GID
Definition of the return code FAIL_DROP_GID.
#define GVM_DROP_PRIVILEGES_FAIL_UNKNOWN_USER
Definition of the return code FAIL_UNKNOWN_USER.
#define GVM_DROP_PRIVILEGES_ERROR_ALREADY_SET
Definition of the return code ERROR_ALREADY_SET.
#define GVM_DROP_PRIVILEGES_FAIL_DROP_UID
Definition of the return code FAIL_DROP_UID.
#define GVM_DROP_PRIVILEGES_FAIL_SUPPLEMENTARY
Definition of the return code FAIL_SUPPLEMENTARY.
#define GVM_DROP_PRIVILEGES_OK
Definition of the return code OK.
#define GVM_DROP_PRIVILEGES
The GQuark for privilege dropping errors.
#define GVM_DROP_PRIVILEGES_FAIL_NOT_ROOT
Definition of the return code FAIL_NOT_ROOT.