1 /*-
2  * Copyright (c) 1998 Michael Smith
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 /*
28  * The unified bootloader passes us a pointer to a preserved copy of
29  * bootstrap/kernel environment variables.  We convert them to a
30  * dynamic array of strings later when the VM subsystem is up.
31  *
32  * We make these available through the kenv(2) syscall for userland
33  * and through getenv()/freeenv() setenv() unsetenv() testenv() for
34  * the kernel.
35  */
36 
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD: stable/10/sys/kern/kern_environment.c 294683 2016-01-24 21:04:06Z ian $");
39 
40 #include <sys/types.h>
41 #include <sys/param.h>
42 #include <sys/proc.h>
43 #include <sys/queue.h>
44 #include <sys/lock.h>
45 #include <sys/malloc.h>
46 #include <sys/mutex.h>
47 #include <sys/priv.h>
48 #include <sys/kernel.h>
49 #include <sys/systm.h>
50 #include <sys/sysent.h>
51 #include <sys/sysproto.h>
52 #include <sys/libkern.h>
53 #include <sys/kenv.h>
54 
55 #include <security/mac/mac_framework.h>
56 
57 static MALLOC_DEFINE(M_KENV, "kenv", "kernel environment");
58 
59 #define KENV_SIZE	512	/* Maximum number of environment strings */
60 
61 /* pointer to the static environment */
62 char		*kern_envp;
63 static int	env_len;
64 static int	env_pos;
65 static char	*kernenv_next(char *);
66 
67 /* dynamic environment variables */
68 char		**kenvp;
69 struct mtx	kenv_lock;
70 
71 /*
72  * No need to protect this with a mutex since SYSINITS are single threaded.
73  */
74 int	dynamic_kenv = 0;
75 
76 #define KENV_CHECK	if (!dynamic_kenv) \
77 			    panic("%s: called before SI_SUB_KMEM", __func__)
78 
79 int
sys_kenv(td,uap)80 sys_kenv(td, uap)
81 	struct thread *td;
82 	struct kenv_args /* {
83 		int what;
84 		const char *name;
85 		char *value;
86 		int len;
87 	} */ *uap;
88 {
89 	char *name, *value, *buffer = NULL;
90 	size_t len, done, needed, buflen;
91 	int error, i;
92 
93 	KASSERT(dynamic_kenv, ("kenv: dynamic_kenv = 0"));
94 
95 	error = 0;
96 	if (uap->what == KENV_DUMP) {
97 #ifdef MAC
98 		error = mac_kenv_check_dump(td->td_ucred);
99 		if (error)
100 			return (error);
101 #endif
102 		done = needed = 0;
103 		buflen = uap->len;
104 		if (buflen > KENV_SIZE * (KENV_MNAMELEN + KENV_MVALLEN + 2))
105 			buflen = KENV_SIZE * (KENV_MNAMELEN +
106 			    KENV_MVALLEN + 2);
107 		if (uap->len > 0 && uap->value != NULL)
108 			buffer = malloc(buflen, M_TEMP, M_WAITOK|M_ZERO);
109 		mtx_lock(&kenv_lock);
110 		for (i = 0; kenvp[i] != NULL; i++) {
111 			len = strlen(kenvp[i]) + 1;
112 			needed += len;
113 			len = min(len, buflen - done);
114 			/*
115 			 * If called with a NULL or insufficiently large
116 			 * buffer, just keep computing the required size.
117 			 */
118 			if (uap->value != NULL && buffer != NULL && len > 0) {
119 				bcopy(kenvp[i], buffer + done, len);
120 				done += len;
121 			}
122 		}
123 		mtx_unlock(&kenv_lock);
124 		if (buffer != NULL) {
125 			error = copyout(buffer, uap->value, done);
126 			free(buffer, M_TEMP);
127 		}
128 		td->td_retval[0] = ((done == needed) ? 0 : needed);
129 		return (error);
130 	}
131 
132 	switch (uap->what) {
133 	case KENV_SET:
134 		error = priv_check(td, PRIV_KENV_SET);
135 		if (error)
136 			return (error);
137 		break;
138 
139 	case KENV_UNSET:
140 		error = priv_check(td, PRIV_KENV_UNSET);
141 		if (error)
142 			return (error);
143 		break;
144 	}
145 
146 	name = malloc(KENV_MNAMELEN + 1, M_TEMP, M_WAITOK);
147 
148 	error = copyinstr(uap->name, name, KENV_MNAMELEN + 1, NULL);
149 	if (error)
150 		goto done;
151 
152 	switch (uap->what) {
153 	case KENV_GET:
154 #ifdef MAC
155 		error = mac_kenv_check_get(td->td_ucred, name);
156 		if (error)
157 			goto done;
158 #endif
159 		value = getenv(name);
160 		if (value == NULL) {
161 			error = ENOENT;
162 			goto done;
163 		}
164 		len = strlen(value) + 1;
165 		if (len > uap->len)
166 			len = uap->len;
167 		error = copyout(value, uap->value, len);
168 		freeenv(value);
169 		if (error)
170 			goto done;
171 		td->td_retval[0] = len;
172 		break;
173 	case KENV_SET:
174 		len = uap->len;
175 		if (len < 1) {
176 			error = EINVAL;
177 			goto done;
178 		}
179 		if (len > KENV_MVALLEN + 1)
180 			len = KENV_MVALLEN + 1;
181 		value = malloc(len, M_TEMP, M_WAITOK);
182 		error = copyinstr(uap->value, value, len, NULL);
183 		if (error) {
184 			free(value, M_TEMP);
185 			goto done;
186 		}
187 #ifdef MAC
188 		error = mac_kenv_check_set(td->td_ucred, name, value);
189 		if (error == 0)
190 #endif
191 			setenv(name, value);
192 		free(value, M_TEMP);
193 		break;
194 	case KENV_UNSET:
195 #ifdef MAC
196 		error = mac_kenv_check_unset(td->td_ucred, name);
197 		if (error)
198 			goto done;
199 #endif
200 		error = unsetenv(name);
201 		if (error)
202 			error = ENOENT;
203 		break;
204 	default:
205 		error = EINVAL;
206 		break;
207 	}
208 done:
209 	free(name, M_TEMP);
210 	return (error);
211 }
212 
213 /*
214  * Populate the initial kernel environment.
215  *
216  * This is called very early in MD startup, either to provide a copy of the
217  * environment obtained from a boot loader, or to provide an empty buffer into
218  * which MD code can store an initial environment using kern_setenv() calls.
219  *
220  * If the global envmode is 1, the environment is initialized from the global
221  * static_env[], regardless of the arguments passed.  This implements the env
222  * keyword described in config(5).  In this case env_pos is set to env_len,
223  * causing kern_setenv() to return -1 (if len > 0) or panic (if len == 0) until
224  * the dynamic environment is available.  The envmode and static_env variables
225  * are defined in env.c which is generated by config(8).
226  *
227  * If len is non-zero, the caller is providing an empty buffer.  The caller will
228  * subsequently use kern_setenv() to add up to len bytes of initial environment
229  * before the dynamic environment is available.
230  *
231  * If len is zero, the caller is providing a pre-loaded buffer containing
232  * environment strings.  Additional strings cannot be added until the dynamic
233  * environment is available.  The memory pointed to must remain stable at least
234  * until sysinit runs init_dynamic_kenv().  If no initial environment is
235  * available from the boot loader, passing a NULL pointer allows the static_env
236  * to be installed if it is configured.
237  */
238 void
init_static_kenv(char * buf,size_t len)239 init_static_kenv(char *buf, size_t len)
240 {
241 
242 	if (envmode == 1) {
243 		kern_envp = static_env;
244 		env_len = len;
245 		env_pos = len;
246 	} else {
247 		kern_envp = buf;
248 		env_len = len;
249 		env_pos = 0;
250 	}
251 }
252 
253 /*
254  * Setup the dynamic kernel environment.
255  */
256 static void
init_dynamic_kenv(void * data __unused)257 init_dynamic_kenv(void *data __unused)
258 {
259 	char *cp;
260 	size_t len;
261 	int i;
262 
263 	kenvp = malloc((KENV_SIZE + 1) * sizeof(char *), M_KENV,
264 		M_WAITOK | M_ZERO);
265 	i = 0;
266 	if (kern_envp && *kern_envp != '\0') {
267 		for (cp = kern_envp; cp != NULL; cp = kernenv_next(cp)) {
268 			len = strlen(cp) + 1;
269 			if (len > KENV_MNAMELEN + 1 + KENV_MVALLEN + 1) {
270 				printf(
271 				"WARNING: too long kenv string, ignoring %s\n",
272 				    cp);
273 				continue;
274 			}
275 			if (i < KENV_SIZE) {
276 				kenvp[i] = malloc(len, M_KENV, M_WAITOK);
277 				strcpy(kenvp[i++], cp);
278 			} else
279 				printf(
280 				"WARNING: too many kenv strings, ignoring %s\n",
281 				    cp);
282 		}
283 	}
284 	kenvp[i] = NULL;
285 
286 	mtx_init(&kenv_lock, "kernel environment", NULL, MTX_DEF);
287 	dynamic_kenv = 1;
288 }
289 SYSINIT(kenv, SI_SUB_KMEM, SI_ORDER_ANY, init_dynamic_kenv, NULL);
290 
291 void
freeenv(char * env)292 freeenv(char *env)
293 {
294 
295 	if (dynamic_kenv)
296 		free(env, M_KENV);
297 }
298 
299 /*
300  * Internal functions for string lookup.
301  */
302 static char *
_getenv_dynamic(const char * name,int * idx)303 _getenv_dynamic(const char *name, int *idx)
304 {
305 	char *cp;
306 	int len, i;
307 
308 	mtx_assert(&kenv_lock, MA_OWNED);
309 	len = strlen(name);
310 	for (cp = kenvp[0], i = 0; cp != NULL; cp = kenvp[++i]) {
311 		if ((strncmp(cp, name, len) == 0) &&
312 		    (cp[len] == '=')) {
313 			if (idx != NULL)
314 				*idx = i;
315 			return (cp + len + 1);
316 		}
317 	}
318 	return (NULL);
319 }
320 
321 static char *
_getenv_static(const char * name)322 _getenv_static(const char *name)
323 {
324 	char *cp, *ep;
325 	int len;
326 
327 	for (cp = kern_envp; cp != NULL; cp = kernenv_next(cp)) {
328 		for (ep = cp; (*ep != '=') && (*ep != 0); ep++)
329 			;
330 		if (*ep != '=')
331 			continue;
332 		len = ep - cp;
333 		ep++;
334 		if (!strncmp(name, cp, len) && name[len] == 0)
335 			return (ep);
336 	}
337 	return (NULL);
338 }
339 
340 /*
341  * Look up an environment variable by name.
342  * Return a pointer to the string if found.
343  * The pointer has to be freed with freeenv()
344  * after use.
345  */
346 char *
getenv(const char * name)347 getenv(const char *name)
348 {
349 	char buf[KENV_MNAMELEN + 1 + KENV_MVALLEN + 1];
350 	char *ret;
351 
352 	if (dynamic_kenv) {
353 		if (getenv_string(name, buf, sizeof(buf))) {
354 			ret = strdup(buf, M_KENV);
355 		} else {
356 			ret = NULL;
357 			WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
358 			    "getenv");
359 		}
360 	} else
361 		ret = _getenv_static(name);
362 	return (ret);
363 }
364 
365 /*
366  * Test if an environment variable is defined.
367  */
368 int
testenv(const char * name)369 testenv(const char *name)
370 {
371 	char *cp;
372 
373 	if (dynamic_kenv) {
374 		mtx_lock(&kenv_lock);
375 		cp = _getenv_dynamic(name, NULL);
376 		mtx_unlock(&kenv_lock);
377 	} else
378 		cp = _getenv_static(name);
379 	if (cp != NULL)
380 		return (1);
381 	return (0);
382 }
383 
384 static int
setenv_static(const char * name,const char * value)385 setenv_static(const char *name, const char *value)
386 {
387 	int len;
388 
389 	if (env_pos >= env_len)
390 		return (-1);
391 
392 	/* Check space for x=y and two nuls */
393 	len = strlen(name) + strlen(value);
394 	if (len + 3 < env_len - env_pos) {
395 		len = sprintf(&kern_envp[env_pos], "%s=%s", name, value);
396 		env_pos += len+1;
397 		kern_envp[env_pos] = '\0';
398 		return (0);
399 	} else
400 		return (-1);
401 
402 }
403 
404 /*
405  * Set an environment variable by name.
406  */
407 int
setenv(const char * name,const char * value)408 setenv(const char *name, const char *value)
409 {
410 	char *buf, *cp, *oldenv;
411 	int namelen, vallen, i;
412 
413 	if (dynamic_kenv == 0 && env_len > 0)
414 		return (setenv_static(name, value));
415 
416 	KENV_CHECK;
417 
418 	namelen = strlen(name) + 1;
419 	if (namelen > KENV_MNAMELEN + 1)
420 		return (-1);
421 	vallen = strlen(value) + 1;
422 	if (vallen > KENV_MVALLEN + 1)
423 		return (-1);
424 	buf = malloc(namelen + vallen, M_KENV, M_WAITOK);
425 	sprintf(buf, "%s=%s", name, value);
426 
427 	mtx_lock(&kenv_lock);
428 	cp = _getenv_dynamic(name, &i);
429 	if (cp != NULL) {
430 		oldenv = kenvp[i];
431 		kenvp[i] = buf;
432 		mtx_unlock(&kenv_lock);
433 		free(oldenv, M_KENV);
434 	} else {
435 		/* We add the option if it wasn't found */
436 		for (i = 0; (cp = kenvp[i]) != NULL; i++)
437 			;
438 
439 		/* Bounds checking */
440 		if (i < 0 || i >= KENV_SIZE) {
441 			free(buf, M_KENV);
442 			mtx_unlock(&kenv_lock);
443 			return (-1);
444 		}
445 
446 		kenvp[i] = buf;
447 		kenvp[i + 1] = NULL;
448 		mtx_unlock(&kenv_lock);
449 	}
450 	return (0);
451 }
452 
453 /*
454  * Unset an environment variable string.
455  */
456 int
unsetenv(const char * name)457 unsetenv(const char *name)
458 {
459 	char *cp, *oldenv;
460 	int i, j;
461 
462 	KENV_CHECK;
463 
464 	mtx_lock(&kenv_lock);
465 	cp = _getenv_dynamic(name, &i);
466 	if (cp != NULL) {
467 		oldenv = kenvp[i];
468 		for (j = i + 1; kenvp[j] != NULL; j++)
469 			kenvp[i++] = kenvp[j];
470 		kenvp[i] = NULL;
471 		mtx_unlock(&kenv_lock);
472 		free(oldenv, M_KENV);
473 		return (0);
474 	}
475 	mtx_unlock(&kenv_lock);
476 	return (-1);
477 }
478 
479 /*
480  * Return a string value from an environment variable.
481  */
482 int
getenv_string(const char * name,char * data,int size)483 getenv_string(const char *name, char *data, int size)
484 {
485 	char *cp;
486 
487 	if (dynamic_kenv) {
488 		mtx_lock(&kenv_lock);
489 		cp = _getenv_dynamic(name, NULL);
490 		if (cp != NULL)
491 			strlcpy(data, cp, size);
492 		mtx_unlock(&kenv_lock);
493 	} else {
494 		cp = _getenv_static(name);
495 		if (cp != NULL)
496 			strlcpy(data, cp, size);
497 	}
498 	return (cp != NULL);
499 }
500 
501 /*
502  * Return an integer value from an environment variable.
503  */
504 int
getenv_int(const char * name,int * data)505 getenv_int(const char *name, int *data)
506 {
507 	quad_t tmp;
508 	int rval;
509 
510 	rval = getenv_quad(name, &tmp);
511 	if (rval)
512 		*data = (int) tmp;
513 	return (rval);
514 }
515 
516 /*
517  * Return an unsigned integer value from an environment variable.
518  */
519 int
getenv_uint(const char * name,unsigned int * data)520 getenv_uint(const char *name, unsigned int *data)
521 {
522 	quad_t tmp;
523 	int rval;
524 
525 	rval = getenv_quad(name, &tmp);
526 	if (rval)
527 		*data = (unsigned int) tmp;
528 	return (rval);
529 }
530 
531 /*
532  * Return a long value from an environment variable.
533  */
534 int
getenv_long(const char * name,long * data)535 getenv_long(const char *name, long *data)
536 {
537 	quad_t tmp;
538 	int rval;
539 
540 	rval = getenv_quad(name, &tmp);
541 	if (rval)
542 		*data = (long) tmp;
543 	return (rval);
544 }
545 
546 /*
547  * Return an unsigned long value from an environment variable.
548  */
549 int
getenv_ulong(const char * name,unsigned long * data)550 getenv_ulong(const char *name, unsigned long *data)
551 {
552 	quad_t tmp;
553 	int rval;
554 
555 	rval = getenv_quad(name, &tmp);
556 	if (rval)
557 		*data = (unsigned long) tmp;
558 	return (rval);
559 }
560 
561 /*
562  * Return a quad_t value from an environment variable.
563  */
564 int
getenv_quad(const char * name,quad_t * data)565 getenv_quad(const char *name, quad_t *data)
566 {
567 	char	value[KENV_MNAMELEN + 1 + KENV_MVALLEN + 1];
568 	char	*vtp;
569 	quad_t	iv;
570 
571 	if (!getenv_string(name, value, sizeof(value)))
572 		return (0);
573 	iv = strtoq(value, &vtp, 0);
574 	if (vtp == value || (vtp[0] != '\0' && vtp[1] != '\0'))
575 		return (0);
576 	switch (vtp[0]) {
577 	case 't': case 'T':
578 		iv *= 1024;
579 	case 'g': case 'G':
580 		iv *= 1024;
581 	case 'm': case 'M':
582 		iv *= 1024;
583 	case 'k': case 'K':
584 		iv *= 1024;
585 	case '\0':
586 		break;
587 	default:
588 		return (0);
589 	}
590 	*data = iv;
591 	return (1);
592 }
593 
594 /*
595  * Find the next entry after the one which (cp) falls within, return a
596  * pointer to its start or NULL if there are no more.
597  */
598 static char *
kernenv_next(char * cp)599 kernenv_next(char *cp)
600 {
601 
602 	if (cp != NULL) {
603 		while (*cp != 0)
604 			cp++;
605 		cp++;
606 		if (*cp == 0)
607 			cp = NULL;
608 	}
609 	return (cp);
610 }
611 
612 void
tunable_int_init(void * data)613 tunable_int_init(void *data)
614 {
615 	struct tunable_int *d = (struct tunable_int *)data;
616 
617 	TUNABLE_INT_FETCH(d->path, d->var);
618 }
619 
620 void
tunable_long_init(void * data)621 tunable_long_init(void *data)
622 {
623 	struct tunable_long *d = (struct tunable_long *)data;
624 
625 	TUNABLE_LONG_FETCH(d->path, d->var);
626 }
627 
628 void
tunable_ulong_init(void * data)629 tunable_ulong_init(void *data)
630 {
631 	struct tunable_ulong *d = (struct tunable_ulong *)data;
632 
633 	TUNABLE_ULONG_FETCH(d->path, d->var);
634 }
635 
636 void
tunable_quad_init(void * data)637 tunable_quad_init(void *data)
638 {
639 	struct tunable_quad *d = (struct tunable_quad *)data;
640 
641 	TUNABLE_QUAD_FETCH(d->path, d->var);
642 }
643 
644 void
tunable_str_init(void * data)645 tunable_str_init(void *data)
646 {
647 	struct tunable_str *d = (struct tunable_str *)data;
648 
649 	TUNABLE_STR_FETCH(d->path, d->var, d->size);
650 }
651