]> code.delx.au - pulseaudio/blob - polyp/caps.c
4ecb5848df174738280345e633a27328de892963
[pulseaudio] / polyp / caps.c
1 /* $Id$ */
2
3 /***
4 This file is part of polypaudio.
5
6 polypaudio is free software; you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as published
8 by the Free Software Foundation; either version 2 of the License,
9 or (at your option) any later version.
10
11 polypaudio is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with polypaudio; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19 USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <assert.h>
27 #include <unistd.h>
28 #include <errno.h>
29 #include <string.h>
30
31 #ifdef HAVE_SYS_CAPABILITY_H
32 #include <sys/capability.h>
33 #endif
34
35 #include "log.h"
36 #include "caps.h"
37
38 #ifdef HAVE_GETUID
39
40 /* Drop root rights when called SUID root */
41 void pa_drop_root(void) {
42 uid_t uid = getuid();
43
44 if (uid == 0 || geteuid() != 0)
45 return;
46
47 pa_log_info(__FILE__": dropping root rights.\n");
48
49 #if defined(HAVE_SETRESUID)
50 setresuid(uid, uid, uid);
51 #elif defined(HAVE_SETREUID)
52 setreuid(uid, uid);
53 #else
54 setuid(uid);
55 seteuid(uid);
56 #endif
57 }
58
59 #else
60
61 void pa_drop_root(void) {
62 }
63
64 #endif
65
66 #ifdef HAVE_SYS_CAPABILITY_H
67
68 /* Limit capabilities set to CAPSYS_NICE */
69 int pa_limit_caps(void) {
70 int r = -1;
71 cap_t caps;
72 cap_value_t nice_cap = CAP_SYS_NICE;
73
74 caps = cap_init();
75 assert(caps);
76
77 cap_clear(caps);
78
79 cap_set_flag(caps, CAP_EFFECTIVE, 1, &nice_cap, CAP_SET);
80 cap_set_flag(caps, CAP_PERMITTED, 1, &nice_cap, CAP_SET);
81
82 if (cap_set_proc(caps) < 0)
83 goto fail;
84
85 pa_log_info(__FILE__": dropped capabilities successfully.\n");
86
87 r = 0;
88
89 fail:
90 cap_free (caps);
91
92 return r;
93 }
94
95 /* Drop all capabilities, effectively becoming a normal user */
96 int pa_drop_caps(void) {
97 cap_t caps;
98 int r = -1;
99
100 caps = cap_init();
101 assert(caps);
102
103 cap_clear(caps);
104
105 if (cap_set_proc(caps) < 0) {
106 pa_log(__FILE__": failed to drop capabilities: %s\n", strerror(errno));
107 goto fail;
108 }
109
110 r = 0;
111
112 fail:
113 cap_free (caps);
114
115 return r;
116 }
117
118 #else
119
120 /* NOOPs in case capabilities are not available. */
121 int pa_limit_caps(void) {
122 return 0;
123 }
124
125 int pa_drop_caps(void) {
126 pa_drop_root();
127 return 0;
128 }
129
130 #endif
131