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