param: Use set_variable instead of set_variable_helper in lp_do_parameter
[Samba.git] / lib / util / unix_privs.c
blob3b00df5349bdc884efbf486e2126deb2bc1ad079
1 /*
2 Unix SMB/CIFS implementation.
4 gain/lose root privileges
6 Copyright (C) Andrew Tridgell 2004
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include "includes.h"
23 #include "system/passwd.h"
25 #ifdef HAVE_UNISTD_H
26 #include <unistd.h>
27 #endif
29 #include "../lib/util/unix_privs.h"
30 #include "../lib/util/setid.h"
32 /**
33 * @file
34 * @brief Gaining/losing root privileges
38 there are times when smbd needs to temporarily gain root privileges
39 to do some operation. To do this you call root_privileges(), which
40 returns a talloc handle. To restore your previous privileges
41 talloc_free() this pointer.
43 Note that this call is considered successful even if it does not
44 manage to gain root privileges, but it will call smb_abort() if it
45 fails to restore the privileges afterwards. The logic is that
46 failing to gain root access can be caught by whatever operation
47 needs to be run as root failing, but failing to lose the root
48 privileges is dangerous.
50 This also means that this code is safe to be called from completely
51 unprivileged processes.
54 struct saved_state {
55 uid_t uid;
58 static int privileges_destructor(struct saved_state *s)
60 if (geteuid() != s->uid &&
61 samba_seteuid(s->uid) != 0) {
62 smb_panic("Failed to restore privileges");
64 return 0;
67 /**
68 * Obtain root privileges for the current process.
70 * The privileges can be dropped by talloc_free()-ing the
71 * token returned by this function
73 void *root_privileges(void)
75 struct saved_state *s;
76 s = talloc(NULL, struct saved_state);
77 if (!s) return NULL;
78 s->uid = geteuid();
79 if (s->uid != 0) {
80 samba_seteuid(0);
82 talloc_set_destructor(s, privileges_destructor);
83 return s;
86 uid_t root_privileges_original_uid(void *s)
88 struct saved_state *saved = talloc_get_type_abort(s, struct saved_state);
89 return saved->uid;