xref: /freebsd/lib/libc/gen/setmode.c (revision 5ca8e32633c4ffbbcd6762e5888b6a4ba0708c6c)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1989, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Dave Borman at Cray Research, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include "namespace.h"
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <sys/sysctl.h>
39 
40 #include <ctype.h>
41 #include <errno.h>
42 #include <limits.h>
43 #include <signal.h>
44 #include <stddef.h>
45 #include <stdlib.h>
46 #include <unistd.h>
47 
48 #ifdef SETMODE_DEBUG
49 #include <stdio.h>
50 #endif
51 #include "un-namespace.h"
52 #include "libc_private.h"
53 
54 #define	SET_LEN	6		/* initial # of bitcmd struct to malloc */
55 #define	SET_LEN_INCR 4		/* # of bitcmd structs to add as needed */
56 
57 typedef struct bitcmd {
58 	char	cmd;
59 	char	cmd2;
60 	mode_t	bits;
61 } BITCMD;
62 
63 #define	CMD2_CLR	0x01
64 #define	CMD2_SET	0x02
65 #define	CMD2_GBITS	0x04
66 #define	CMD2_OBITS	0x08
67 #define	CMD2_UBITS	0x10
68 
69 static mode_t	 get_current_umask(void);
70 static BITCMD	*addcmd(BITCMD *, mode_t, mode_t, mode_t, mode_t);
71 static void	 compress_mode(BITCMD *);
72 #ifdef SETMODE_DEBUG
73 static void	 dumpmode(BITCMD *);
74 #endif
75 
76 /*
77  * Given the old mode and an array of bitcmd structures, apply the operations
78  * described in the bitcmd structures to the old mode, and return the new mode.
79  * Note that there is no '=' command; a strict assignment is just a '-' (clear
80  * bits) followed by a '+' (set bits).
81  */
82 mode_t
83 getmode(const void *bbox, mode_t omode)
84 {
85 	const BITCMD *set;
86 	mode_t clrval, newmode, value;
87 
88 	set = (const BITCMD *)bbox;
89 	newmode = omode;
90 	for (value = 0;; set++)
91 		switch(set->cmd) {
92 		/*
93 		 * When copying the user, group or other bits around, we "know"
94 		 * where the bits are in the mode so that we can do shifts to
95 		 * copy them around.  If we don't use shifts, it gets real
96 		 * grundgy with lots of single bit checks and bit sets.
97 		 */
98 		case 'u':
99 			value = (newmode & S_IRWXU) >> 6;
100 			goto common;
101 
102 		case 'g':
103 			value = (newmode & S_IRWXG) >> 3;
104 			goto common;
105 
106 		case 'o':
107 			value = newmode & S_IRWXO;
108 common:			if (set->cmd2 & CMD2_CLR) {
109 				clrval =
110 				    (set->cmd2 & CMD2_SET) ?  S_IRWXO : value;
111 				if (set->cmd2 & CMD2_UBITS)
112 					newmode &= ~((clrval<<6) & set->bits);
113 				if (set->cmd2 & CMD2_GBITS)
114 					newmode &= ~((clrval<<3) & set->bits);
115 				if (set->cmd2 & CMD2_OBITS)
116 					newmode &= ~(clrval & set->bits);
117 			}
118 			if (set->cmd2 & CMD2_SET) {
119 				if (set->cmd2 & CMD2_UBITS)
120 					newmode |= (value<<6) & set->bits;
121 				if (set->cmd2 & CMD2_GBITS)
122 					newmode |= (value<<3) & set->bits;
123 				if (set->cmd2 & CMD2_OBITS)
124 					newmode |= value & set->bits;
125 			}
126 			break;
127 
128 		case '+':
129 			newmode |= set->bits;
130 			break;
131 
132 		case '-':
133 			newmode &= ~set->bits;
134 			break;
135 
136 		case 'X':
137 			if (omode & (S_IFDIR|S_IXUSR|S_IXGRP|S_IXOTH))
138 				newmode |= set->bits;
139 			break;
140 
141 		case '\0':
142 		default:
143 #ifdef SETMODE_DEBUG
144 			(void)printf("getmode:%04o -> %04o\n", omode, newmode);
145 #endif
146 			return (newmode);
147 		}
148 }
149 
150 #define	ADDCMD(a, b, c, d)						\
151 	if (set >= endset) {						\
152 		BITCMD *newset;						\
153 		setlen += SET_LEN_INCR;					\
154 		newset = reallocarray(saveset, setlen, sizeof(BITCMD));	\
155 		if (newset == NULL)					\
156 			goto out;					\
157 		set = newset + (set - saveset);				\
158 		saveset = newset;					\
159 		endset = newset + (setlen - 2);				\
160 	}								\
161 	set = addcmd(set, (mode_t)(a), (mode_t)(b), (mode_t)(c), (d))
162 
163 #define	STANDARD_BITS	(S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
164 
165 void *
166 setmode(const char *p)
167 {
168 	int serrno;
169 	char op, *ep;
170 	BITCMD *set, *saveset, *endset;
171 	mode_t mask, perm, permXbits, who;
172 	long perml;
173 	int equalopdone;
174 	u_int setlen;
175 
176 	if (!*p) {
177 		errno = EINVAL;
178 		return (NULL);
179 	}
180 
181 	/*
182 	 * Get a copy of the mask for the permissions that are mask relative.
183 	 * Flip the bits, we want what's not set.
184 	 */
185 	mask = ~get_current_umask();
186 
187 	setlen = SET_LEN + 2;
188 
189 	if ((set = malloc(setlen * sizeof(BITCMD))) == NULL)
190 		return (NULL);
191 	saveset = set;
192 	endset = set + (setlen - 2);
193 
194 	/*
195 	 * If an absolute number, get it and return; disallow non-octal digits
196 	 * or illegal bits.
197 	 */
198 	if (isdigit((unsigned char)*p)) {
199 		errno = 0;
200 		perml = strtol(p, &ep, 8);
201 		if (*ep) {
202 			errno = EINVAL;
203 			goto out;
204 		}
205 		if (errno == ERANGE && (perml == LONG_MAX || perml == LONG_MIN))
206 			goto out;
207 		if (perml & ~(STANDARD_BITS|S_ISTXT)) {
208 			errno = EINVAL;
209 			goto out;
210 		}
211 		perm = (mode_t)perml;
212 		ADDCMD('=', (STANDARD_BITS|S_ISTXT), perm, mask);
213 		set->cmd = 0;
214 		return (saveset);
215 	}
216 
217 	/*
218 	 * Build list of structures to set/clear/copy bits as described by
219 	 * each clause of the symbolic mode.
220 	 */
221 	equalopdone = 0;
222 	for (;;) {
223 		/* First, find out which bits might be modified. */
224 		for (who = 0;; ++p) {
225 			switch (*p) {
226 			case 'a':
227 				who |= STANDARD_BITS;
228 				break;
229 			case 'u':
230 				who |= S_ISUID|S_IRWXU;
231 				break;
232 			case 'g':
233 				who |= S_ISGID|S_IRWXG;
234 				break;
235 			case 'o':
236 				who |= S_IRWXO;
237 				break;
238 			default:
239 				goto getop;
240 			}
241 		}
242 
243 getop:		if ((op = *p++) != '+' && op != '-' && op != '=') {
244 			errno = EINVAL;
245 			goto out;
246 		}
247 		if (op == '=')
248 			equalopdone = 0;
249 
250 		who &= ~S_ISTXT;
251 		for (perm = 0, permXbits = 0;; ++p) {
252 			switch (*p) {
253 			case 'r':
254 				perm |= S_IRUSR|S_IRGRP|S_IROTH;
255 				break;
256 			case 's':
257 				/* If only "other" bits ignore set-id. */
258 				if (!who || who & ~S_IRWXO)
259 					perm |= S_ISUID|S_ISGID;
260 				break;
261 			case 't':
262 				/* If only "other" bits ignore sticky. */
263 				if (!who || who & ~S_IRWXO) {
264 					who |= S_ISTXT;
265 					perm |= S_ISTXT;
266 				}
267 				break;
268 			case 'w':
269 				perm |= S_IWUSR|S_IWGRP|S_IWOTH;
270 				break;
271 			case 'X':
272 				permXbits = S_IXUSR|S_IXGRP|S_IXOTH;
273 				break;
274 			case 'x':
275 				perm |= S_IXUSR|S_IXGRP|S_IXOTH;
276 				break;
277 			case 'u':
278 			case 'g':
279 			case 'o':
280 				/*
281 				 * When ever we hit 'u', 'g', or 'o', we have
282 				 * to flush out any partial mode that we have,
283 				 * and then do the copying of the mode bits.
284 				 */
285 				if (perm) {
286 					ADDCMD(op, who, perm, mask);
287 					perm = 0;
288 				}
289 				if (op == '=')
290 					equalopdone = 1;
291 				if (op == '+' && permXbits) {
292 					ADDCMD('X', who, permXbits, mask);
293 					permXbits = 0;
294 				}
295 				ADDCMD(*p, who, op, mask);
296 				break;
297 
298 			default:
299 				/*
300 				 * Add any permissions that we haven't already
301 				 * done.
302 				 */
303 				if (perm || (op == '=' && !equalopdone)) {
304 					if (op == '=')
305 						equalopdone = 1;
306 					ADDCMD(op, who, perm, mask);
307 					perm = 0;
308 				}
309 				if (permXbits) {
310 					ADDCMD('X', who, permXbits, mask);
311 					permXbits = 0;
312 				}
313 				goto apply;
314 			}
315 		}
316 
317 apply:		if (!*p)
318 			break;
319 		if (*p != ',')
320 			goto getop;
321 		++p;
322 	}
323 	set->cmd = 0;
324 #ifdef SETMODE_DEBUG
325 	(void)printf("Before compress_mode()\n");
326 	dumpmode(saveset);
327 #endif
328 	compress_mode(saveset);
329 #ifdef SETMODE_DEBUG
330 	(void)printf("After compress_mode()\n");
331 	dumpmode(saveset);
332 #endif
333 	return (saveset);
334 out:
335 	serrno = errno;
336 	free(saveset);
337 	errno = serrno;
338 	return NULL;
339 }
340 
341 static mode_t
342 get_current_umask(void)
343 {
344 	sigset_t sigset, sigoset;
345 	size_t len;
346 	mode_t mask;
347 	u_short smask;
348 
349 #ifdef KERN_PROC_UMASK
350 	/*
351 	 * First try requesting the umask without temporarily modifying it.
352 	 * Note that this does not work if the sysctl
353 	 * security.bsd.unprivileged_proc_debug is set to 0.
354 	 */
355 	len = sizeof(smask);
356 	if (sysctl((int[4]){ CTL_KERN, KERN_PROC, KERN_PROC_UMASK, 0 },
357 	    4, &smask, &len, NULL, 0) == 0)
358 		return (smask);
359 #endif
360 	/*
361 	 * Since it's possible that the caller is opening files inside a signal
362 	 * handler, protect them as best we can.
363 	 */
364 	sigfillset(&sigset);
365 	(void)__libc_sigprocmask(SIG_BLOCK, &sigset, &sigoset);
366 	(void)umask(mask = umask(0));
367 	(void)__libc_sigprocmask(SIG_SETMASK, &sigoset, NULL);
368 	return (mask);
369 }
370 
371 static BITCMD *
372 addcmd(BITCMD *set, mode_t op, mode_t who, mode_t oparg, mode_t mask)
373 {
374 	switch (op) {
375 	case '=':
376 		set->cmd = '-';
377 		set->bits = who ? who : STANDARD_BITS;
378 		set++;
379 
380 		op = '+';
381 		/* FALLTHROUGH */
382 	case '+':
383 	case '-':
384 	case 'X':
385 		set->cmd = op;
386 		set->bits = (who ? who : mask) & oparg;
387 		break;
388 
389 	case 'u':
390 	case 'g':
391 	case 'o':
392 		set->cmd = op;
393 		if (who) {
394 			set->cmd2 = ((who & S_IRUSR) ? CMD2_UBITS : 0) |
395 				    ((who & S_IRGRP) ? CMD2_GBITS : 0) |
396 				    ((who & S_IROTH) ? CMD2_OBITS : 0);
397 			set->bits = (mode_t)~0;
398 		} else {
399 			set->cmd2 = CMD2_UBITS | CMD2_GBITS | CMD2_OBITS;
400 			set->bits = mask;
401 		}
402 
403 		if (oparg == '+')
404 			set->cmd2 |= CMD2_SET;
405 		else if (oparg == '-')
406 			set->cmd2 |= CMD2_CLR;
407 		else if (oparg == '=')
408 			set->cmd2 |= CMD2_SET|CMD2_CLR;
409 		break;
410 	}
411 	return (set + 1);
412 }
413 
414 #ifdef SETMODE_DEBUG
415 static void
416 dumpmode(BITCMD *set)
417 {
418 	for (; set->cmd; ++set)
419 		(void)printf("cmd: '%c' bits %04o%s%s%s%s%s%s\n",
420 		    set->cmd, set->bits, set->cmd2 ? " cmd2:" : "",
421 		    set->cmd2 & CMD2_CLR ? " CLR" : "",
422 		    set->cmd2 & CMD2_SET ? " SET" : "",
423 		    set->cmd2 & CMD2_UBITS ? " UBITS" : "",
424 		    set->cmd2 & CMD2_GBITS ? " GBITS" : "",
425 		    set->cmd2 & CMD2_OBITS ? " OBITS" : "");
426 }
427 #endif
428 
429 /*
430  * Given an array of bitcmd structures, compress by compacting consecutive
431  * '+', '-' and 'X' commands into at most 3 commands, one of each.  The 'u',
432  * 'g' and 'o' commands continue to be separate.  They could probably be
433  * compacted, but it's not worth the effort.
434  */
435 static void
436 compress_mode(BITCMD *set)
437 {
438 	BITCMD *nset;
439 	int setbits, clrbits, Xbits, op;
440 
441 	for (nset = set;;) {
442 		/* Copy over any 'u', 'g' and 'o' commands. */
443 		while ((op = nset->cmd) != '+' && op != '-' && op != 'X') {
444 			*set++ = *nset++;
445 			if (!op)
446 				return;
447 		}
448 
449 		for (setbits = clrbits = Xbits = 0;; nset++) {
450 			if ((op = nset->cmd) == '-') {
451 				clrbits |= nset->bits;
452 				setbits &= ~nset->bits;
453 				Xbits &= ~nset->bits;
454 			} else if (op == '+') {
455 				setbits |= nset->bits;
456 				clrbits &= ~nset->bits;
457 				Xbits &= ~nset->bits;
458 			} else if (op == 'X')
459 				Xbits |= nset->bits & ~setbits;
460 			else
461 				break;
462 		}
463 		if (clrbits) {
464 			set->cmd = '-';
465 			set->cmd2 = 0;
466 			set->bits = clrbits;
467 			set++;
468 		}
469 		if (setbits) {
470 			set->cmd = '+';
471 			set->cmd2 = 0;
472 			set->bits = setbits;
473 			set++;
474 		}
475 		if (Xbits) {
476 			set->cmd = 'X';
477 			set->cmd2 = 0;
478 			set->bits = Xbits;
479 			set++;
480 		}
481 	}
482 }
483