s4: Remove autogenerated attributes from minschema and fullschema output
[Samba/bb.git] / lib / util / unix_privs.c
blobf55e739a9bbaa18e2e5ef07dcfceff1048645e6b
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/filesys.h"
24 #include "../lib/util/unix_privs.h"
26 /**
27 * @file
28 * @brief Gaining/losing root privileges
32 there are times when smbd needs to temporarily gain root privileges
33 to do some operation. To do this you call root_privileges(), which
34 returns a talloc handle. To restore your previous privileges
35 talloc_free() this pointer.
37 Note that this call is considered successful even if it does not
38 manage to gain root privileges, but it will call smb_abort() if it
39 fails to restore the privileges afterwards. The logic is that
40 failing to gain root access can be caught by whatever operation
41 needs to be run as root failing, but failing to lose the root
42 privileges is dangerous.
44 This also means that this code is safe to be called from completely
45 unprivileged processes.
48 struct saved_state {
49 uid_t uid;
52 static int privileges_destructor(struct saved_state *s)
54 if (geteuid() != s->uid &&
55 seteuid(s->uid) != 0) {
56 smb_panic("Failed to restore privileges");
58 return 0;
61 /**
62 * Obtain root privileges for the current process.
64 * The privileges can be dropped by talloc_free()-ing the
65 * token returned by this function
67 void *root_privileges(void)
69 struct saved_state *s;
70 s = talloc(NULL, struct saved_state);
71 if (!s) return NULL;
72 s->uid = geteuid();
73 if (s->uid != 0) {
74 seteuid(0);
76 talloc_set_destructor(s, privileges_destructor);
77 return s;