r23792: convert Samba4 to GPLv3
[sfrench/samba-autobuild/.git] / source4 / lib / util / unix_privs.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    gain/lose root privileges
5
6    Copyright (C) Andrew Tridgell 2004
7    
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.
12    
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.
17    
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/>.
20 */
21
22 #include "includes.h"
23 #include "system/filesys.h"
24
25 /**
26  * @file
27  * @brief Gaining/losing root privileges
28  */
29
30 /*
31   there are times when smbd needs to temporarily gain root privileges
32   to do some operation. To do this you call root_privileges(), which
33   returns a talloc handle. To restore your previous privileges
34   talloc_free() this pointer.
35
36   Note that this call is considered successful even if it does not
37   manage to gain root privileges, but it will call smb_abort() if it
38   fails to restore the privileges afterwards. The logic is that
39   failing to gain root access can be caught by whatever operation
40   needs to be run as root failing, but failing to lose the root
41   privileges is dangerous.
42
43   This also means that this code is safe to be called from completely
44   unprivileged processes.
45 */
46
47 struct saved_state {
48         uid_t uid;
49 };
50
51 static int privileges_destructor(struct saved_state *s)
52 {
53         if (geteuid() != s->uid &&
54             seteuid(s->uid) != 0) {
55                 smb_panic("Failed to restore privileges");
56         }
57         return 0;
58 }
59
60 /**
61  * Obtain root privileges for the current process.
62  *
63  * The privileges can be dropped by talloc_free()-ing the 
64  * token returned by this function
65  */
66 void *root_privileges(void)
67 {
68         struct saved_state *s;
69         s = talloc(NULL, struct saved_state);
70         if (!s) return NULL;
71         s->uid = geteuid();
72         if (s->uid != 0) {
73                 seteuid(0);
74         }
75         talloc_set_destructor(s, privileges_destructor);
76         return s;
77 }