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