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