r13655: Use new name of build header
[samba.git] / source / 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 2 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, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22
23 #include "includes.h"
24 #include "system/filesys.h"
25
26 /*
27   there are times when smbd needs to temporarily gain root privileges
28   to do some operation. To do this you call root_privileges(), which
29   returns a talloc handle. To restore your previous privileges
30   talloc_free() this pointer.
31
32   Note that this call is considered successful even if it does not
33   manage to gain root privileges, but it will call smb_abort() if it
34   fails to restore the privileges afterwards. The logic is that
35   failing to gain root access can be caught by whatever operation
36   needs to be run as root failing, but failing to lose the root
37   privileges is dangerous.
38
39   This also means that this code is safe to be called from completely
40   unprivileged processes.
41 */
42
43 struct saved_state {
44         uid_t uid;
45 };
46
47 static int privileges_destructor(void *ptr)
48 {
49         struct saved_state *s = ptr;
50         if (geteuid() != s->uid &&
51             seteuid(s->uid) != 0) {
52                 smb_panic("Failed to restore privileges");
53         }
54         return 0;
55 }
56
57 void *root_privileges(void)
58 {
59         struct saved_state *s;
60         s = talloc(NULL, struct saved_state);
61         if (!s) return NULL;
62         s->uid = geteuid();
63         if (s->uid != 0) {
64                 seteuid(0);
65         }
66         talloc_set_destructor(s, privileges_destructor);
67         return s;
68 }