GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: lib/libc/gen/login_cap.c Lines: 0 506 0.0 %
Date: 2017-11-07 Branches: 0 430 0.0 %

Line Branch Exec Source
1
/*	$OpenBSD: login_cap.c,v 1.34 2016/03/10 18:30:53 mmcc Exp $	*/
2
3
/*
4
 * Copyright (c) 2000-2004 Todd C. Miller <Todd.Miller@courtesan.com>
5
 *
6
 * Permission to use, copy, modify, and distribute this software for any
7
 * purpose with or without fee is hereby granted, provided that the above
8
 * copyright notice and this permission notice appear in all copies.
9
 *
10
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
 */
18
/*-
19
 * Copyright (c) 1995,1997 Berkeley Software Design, Inc. All rights reserved.
20
 *
21
 * Redistribution and use in source and binary forms, with or without
22
 * modification, are permitted provided that the following conditions
23
 * are met:
24
 * 1. Redistributions of source code must retain the above copyright
25
 *    notice, this list of conditions and the following disclaimer.
26
 * 2. Redistributions in binary form must reproduce the above copyright
27
 *    notice, this list of conditions and the following disclaimer in the
28
 *    documentation and/or other materials provided with the distribution.
29
 * 3. All advertising materials mentioning features or use of this software
30
 *    must display the following acknowledgement:
31
 *	This product includes software developed by Berkeley Software Design,
32
 *	Inc.
33
 * 4. The name of Berkeley Software Design, Inc.  may not be used to endorse
34
 *    or promote products derived from this software without specific prior
35
 *    written permission.
36
 *
37
 * THIS SOFTWARE IS PROVIDED BY BERKELEY SOFTWARE DESIGN, INC. ``AS IS'' AND
38
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
39
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
40
 * ARE DISCLAIMED.  IN NO EVENT SHALL BERKELEY SOFTWARE DESIGN, INC. BE LIABLE
41
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
42
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
43
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
44
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
45
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
46
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47
 * SUCH DAMAGE.
48
 *
49
 *	BSDI $From: login_cap.c,v 2.16 2000/03/22 17:10:55 donn Exp $
50
 */
51
#include <sys/types.h>
52
#include <sys/stat.h>
53
#include <sys/time.h>
54
#include <sys/resource.h>
55
56
#include <err.h>
57
#include <errno.h>
58
#include <fcntl.h>
59
#include <limits.h>
60
#include <login_cap.h>
61
#include <paths.h>
62
#include <pwd.h>
63
#include <stdio.h>
64
#include <stdlib.h>
65
#include <string.h>
66
#include <syslog.h>
67
#include <unistd.h>
68
69
70
static	char *_authtypes[] = { LOGIN_DEFSTYLE, 0 };
71
static	char *expandstr(const char *, const struct passwd *, int);
72
static	int login_setenv(char *, char *, const struct passwd *, int);
73
static	int setuserenv(login_cap_t *, const struct passwd *);
74
static	int setuserpath(login_cap_t *, const struct passwd *);
75
static	u_quad_t multiply(u_quad_t, u_quad_t);
76
static	u_quad_t strtolimit(char *, char **, int);
77
static	u_quad_t strtosize(char *, char **, int);
78
static	int gsetrl(login_cap_t *, int, char *, int);
79
80
login_cap_t *
81
login_getclass(char *class)
82
{
83
	char *classfiles[2] = {NULL, NULL};
84
	login_cap_t *lc;
85
	int res;
86
87
	if (secure_path(_PATH_LOGIN_CONF) == 0)
88
		classfiles[0] = _PATH_LOGIN_CONF;
89
90
	if ((lc = malloc(sizeof(login_cap_t))) == NULL) {
91
		syslog(LOG_ERR, "%s:%d malloc: %m", __FILE__, __LINE__);
92
		return (0);
93
	}
94
95
	lc->lc_cap = 0;
96
	lc->lc_style = 0;
97
98
	if (class == NULL || class[0] == '\0')
99
		class = LOGIN_DEFCLASS;
100
101
    	if ((lc->lc_class = strdup(class)) == NULL) {
102
		syslog(LOG_ERR, "%s:%d strdup: %m", __FILE__, __LINE__);
103
		free(lc);
104
		return (0);
105
	}
106
107
	/*
108
	 * Not having a login.conf file is not an error condition.
109
	 * The individual routines deal reasonably with missing
110
	 * capabilities and use default values.
111
	 */
112
	if (classfiles[0] == NULL)
113
		return(lc);
114
115
	if ((res = cgetent(&lc->lc_cap, classfiles, lc->lc_class)) != 0) {
116
		lc->lc_cap = 0;
117
		switch (res) {
118
		case 1:
119
			syslog(LOG_ERR, "%s: couldn't resolve 'tc'",
120
				lc->lc_class);
121
			break;
122
		case -1:
123
			if ((res = open(classfiles[0], 0)) >= 0)
124
				close(res);
125
			if (strcmp(lc->lc_class, LOGIN_DEFCLASS) == 0 &&
126
			    res < 0)
127
				return (lc);
128
			syslog(LOG_ERR, "%s: unknown class", lc->lc_class);
129
			break;
130
		case -2:
131
			syslog(LOG_ERR, "%s: getting class information: %m",
132
				lc->lc_class);
133
			break;
134
		case -3:
135
			syslog(LOG_ERR, "%s: 'tc' reference loop",
136
				lc->lc_class);
137
			break;
138
		default:
139
			syslog(LOG_ERR, "%s: unexpected cgetent error",
140
				lc->lc_class);
141
			break;
142
		}
143
		free(lc->lc_class);
144
		free(lc);
145
		return (0);
146
	}
147
	return (lc);
148
}
149
DEF_WEAK(login_getclass);
150
151
char *
152
login_getstyle(login_cap_t *lc, char *style, char *atype)
153
{
154
    	char **authtypes = _authtypes;
155
	char *auths, *ta;
156
    	char *f1 = NULL, **f2 = NULL;
157
	int i;
158
159
	/* Silently convert 's/key' -> 'skey' */
160
	if (style && strcmp(style, "s/key") == 0)
161
		style = "skey";
162
163
	free(lc->lc_style);
164
	lc->lc_style = NULL;
165
166
    	if (!atype || !(auths = login_getcapstr(lc, atype, NULL, NULL)))
167
		auths = login_getcapstr(lc, "auth", NULL, NULL);
168
169
	if (auths) {
170
		f1 = ta = auths;	/* auths malloced by login_getcapstr */
171
		i = 2;
172
		while (*ta)
173
			if (*ta++ == ',')
174
				++i;
175
		f2 = authtypes = calloc(sizeof(char *), i);
176
		if (!authtypes) {
177
			syslog(LOG_ERR, "malloc: %m");
178
			free(f1);
179
			return (0);
180
		}
181
		i = 0;
182
		while (*auths) {
183
			authtypes[i] = auths;
184
			while (*auths && *auths != ',')
185
				++auths;
186
			if (*auths)
187
				*auths++ = 0;
188
			if (!*authtypes[i])
189
				authtypes[i] = LOGIN_DEFSTYLE;
190
			++i;
191
		}
192
		authtypes[i] = 0;
193
	}
194
195
	if (!style)
196
		style = authtypes[0];
197
198
	while (*authtypes && strcmp(style, *authtypes))
199
		++authtypes;
200
201
	if (*authtypes) {
202
		lc->lc_style = strdup(*authtypes);
203
		if (lc->lc_style == NULL)
204
			syslog(LOG_ERR, "strdup: %m");
205
	}
206
	free(f1);
207
	free(f2);
208
	return (lc->lc_style);
209
}
210
DEF_WEAK(login_getstyle);
211
212
char *
213
login_getcapstr(login_cap_t *lc, char *cap, char *def, char *e)
214
{
215
	char *res = NULL, *str = e;
216
	int stat;
217
218
	errno = 0;
219
220
    	if (!lc->lc_cap)
221
		return (def);
222
223
	switch (stat = cgetstr(lc->lc_cap, cap, &res)) {
224
	case -1:
225
		str = def;
226
		break;
227
	case -2:
228
		syslog(LOG_ERR, "%s: getting capability %s: %m",
229
		    lc->lc_class, cap);
230
		break;
231
	default:
232
		if (stat >= 0)
233
			str = res;
234
		else
235
			syslog(LOG_ERR,
236
			    "%s: unexpected error with capability %s",
237
			    lc->lc_class, cap);
238
		break;
239
	}
240
241
	if (res != NULL && str != res)
242
		free(res);
243
	return(str);
244
}
245
DEF_WEAK(login_getcapstr);
246
247
quad_t
248
login_getcaptime(login_cap_t *lc, char *cap, quad_t def, quad_t e)
249
{
250
	char *ep;
251
	char *res = NULL, *sres;
252
	int stat;
253
	quad_t q, r;
254
255
	errno = 0;
256
257
    	if (!lc->lc_cap)
258
		return (def);
259
260
	switch (stat = cgetstr(lc->lc_cap, cap, &res)) {
261
	case -1:
262
		free(res);
263
		return (def);
264
	case -2:
265
		free(res);
266
		syslog(LOG_ERR, "%s: getting capability %s: %m",
267
		    lc->lc_class, cap);
268
		errno = ERANGE;
269
		return (e);
270
	default:
271
		if (stat >= 0)
272
			break;
273
		free(res);
274
		syslog(LOG_ERR, "%s: unexpected error with capability %s",
275
		    lc->lc_class, cap);
276
		errno = ERANGE;
277
		return (e);
278
	}
279
280
	errno = 0;
281
282
	if (strcasecmp(res, "infinity") == 0) {
283
		free(res);
284
		return (RLIM_INFINITY);
285
	}
286
287
	q = 0;
288
	sres = res;
289
	while (*res) {
290
		r = strtoll(res, &ep, 0);
291
		if (!ep || ep == res ||
292
		    ((r == QUAD_MIN || r == QUAD_MAX) && errno == ERANGE)) {
293
invalid:
294
			syslog(LOG_ERR, "%s:%s=%s: invalid time",
295
			    lc->lc_class, cap, sres);
296
			free(sres);
297
			errno = ERANGE;
298
			return (e);
299
		}
300
		switch (*ep++) {
301
		case '\0':
302
			--ep;
303
			break;
304
		case 's': case 'S':
305
			break;
306
		case 'm': case 'M':
307
			r *= 60;
308
			break;
309
		case 'h': case 'H':
310
			r *= 60 * 60;
311
			break;
312
		case 'd': case 'D':
313
			r *= 60 * 60 * 24;
314
			break;
315
		case 'w': case 'W':
316
			r *= 60 * 60 * 24 * 7;
317
			break;
318
		case 'y': case 'Y':	/* Pretty absurd */
319
			r *= 60 * 60 * 24 * 365;
320
			break;
321
		default:
322
			goto invalid;
323
		}
324
		res = ep;
325
		q += r;
326
	}
327
	free(sres);
328
	return (q);
329
}
330
DEF_WEAK(login_getcaptime);
331
332
quad_t
333
login_getcapnum(login_cap_t *lc, char *cap, quad_t def, quad_t e)
334
{
335
	char *ep;
336
	char *res = NULL;
337
	int stat;
338
	quad_t q;
339
340
	errno = 0;
341
342
    	if (!lc->lc_cap)
343
		return (def);
344
345
	switch (stat = cgetstr(lc->lc_cap, cap, &res)) {
346
	case -1:
347
		free(res);
348
		return (def);
349
	case -2:
350
		free(res);
351
		syslog(LOG_ERR, "%s: getting capability %s: %m",
352
		    lc->lc_class, cap);
353
		errno = ERANGE;
354
		return (e);
355
	default:
356
		if (stat >= 0)
357
			break;
358
		free(res);
359
		syslog(LOG_ERR, "%s: unexpected error with capability %s",
360
		    lc->lc_class, cap);
361
		errno = ERANGE;
362
		return (e);
363
	}
364
365
	errno = 0;
366
367
	if (strcasecmp(res, "infinity") == 0) {
368
		free(res);
369
		return (RLIM_INFINITY);
370
	}
371
372
    	q = strtoll(res, &ep, 0);
373
	if (!ep || ep == res || ep[0] ||
374
	    ((q == QUAD_MIN || q == QUAD_MAX) && errno == ERANGE)) {
375
		syslog(LOG_ERR, "%s:%s=%s: invalid number",
376
		    lc->lc_class, cap, res);
377
		free(res);
378
		errno = ERANGE;
379
		return (e);
380
	}
381
	free(res);
382
	return (q);
383
}
384
DEF_WEAK(login_getcapnum);
385
386
quad_t
387
login_getcapsize(login_cap_t *lc, char *cap, quad_t def, quad_t e)
388
{
389
	char *ep;
390
	char *res = NULL;
391
	int stat;
392
	quad_t q;
393
394
	errno = 0;
395
396
    	if (!lc->lc_cap)
397
		return (def);
398
399
	switch (stat = cgetstr(lc->lc_cap, cap, &res)) {
400
	case -1:
401
		free(res);
402
		return (def);
403
	case -2:
404
		free(res);
405
		syslog(LOG_ERR, "%s: getting capability %s: %m",
406
		    lc->lc_class, cap);
407
		errno = ERANGE;
408
		return (e);
409
	default:
410
		if (stat >= 0)
411
			break;
412
		free(res);
413
		syslog(LOG_ERR, "%s: unexpected error with capability %s",
414
		    lc->lc_class, cap);
415
		errno = ERANGE;
416
		return (e);
417
	}
418
419
	errno = 0;
420
	q = strtolimit(res, &ep, 0);
421
	if (!ep || ep == res || (ep[0] && ep[1]) ||
422
	    ((q == QUAD_MIN || q == QUAD_MAX) && errno == ERANGE)) {
423
		syslog(LOG_ERR, "%s:%s=%s: invalid size",
424
		    lc->lc_class, cap, res);
425
		free(res);
426
		errno = ERANGE;
427
		return (e);
428
	}
429
	free(res);
430
	return (q);
431
}
432
DEF_WEAK(login_getcapsize);
433
434
int
435
login_getcapbool(login_cap_t *lc, char *cap, u_int def)
436
{
437
    	if (!lc->lc_cap)
438
		return (def);
439
440
	return (cgetcap(lc->lc_cap, cap, ':') != NULL);
441
}
442
DEF_WEAK(login_getcapbool);
443
444
void
445
login_close(login_cap_t *lc)
446
{
447
	if (lc) {
448
		free(lc->lc_class);
449
		free(lc->lc_cap);
450
		free(lc->lc_style);
451
		free(lc);
452
	}
453
}
454
DEF_WEAK(login_close);
455
456
#define	CTIME	1
457
#define	CSIZE	2
458
#define	CNUMB	3
459
460
static struct {
461
	int	what;
462
	int	type;
463
	char *	name;
464
} r_list[] = {
465
	{ RLIMIT_CPU,		CTIME, "cputime", },
466
	{ RLIMIT_FSIZE,		CSIZE, "filesize", },
467
	{ RLIMIT_DATA,		CSIZE, "datasize", },
468
	{ RLIMIT_STACK,		CSIZE, "stacksize", },
469
	{ RLIMIT_RSS,		CSIZE, "memoryuse", },
470
	{ RLIMIT_MEMLOCK,	CSIZE, "memorylocked", },
471
	{ RLIMIT_NPROC,		CNUMB, "maxproc", },
472
	{ RLIMIT_NOFILE,	CNUMB, "openfiles", },
473
	{ RLIMIT_CORE,		CSIZE, "coredumpsize", },
474
#ifdef RLIMIT_VMEM
475
	{ RLIMIT_VMEM,		CSIZE, "vmemoryuse", },
476
#endif
477
	{ -1, 0, 0 }
478
};
479
480
static int
481
gsetrl(login_cap_t *lc, int what, char *name, int type)
482
{
483
	struct rlimit rl;
484
	struct rlimit r;
485
	char name_cur[32];
486
	char name_max[32];
487
    	char *v;
488
	int len;
489
490
	/*
491
	 * If we have no capabilities then there is nothing to do and
492
	 * we can just return success.
493
	 */
494
	if (lc->lc_cap == NULL)
495
		return (0);
496
497
	len = snprintf(name_cur, sizeof name_cur, "%s-cur", name);
498
	if (len < 0 || len >= sizeof name_cur) {
499
		syslog(LOG_ERR, "current resource limit name too large");
500
		return (-1);
501
	}
502
	len = snprintf(name_max, sizeof name_max, "%s-max", name);
503
	if (len < 0 || len >= sizeof name_max) {
504
		syslog(LOG_ERR, "max resource limit name too large");
505
		return (-1);
506
	}
507
508
	if (getrlimit(what, &r)) {
509
		syslog(LOG_ERR, "getting resource limit: %m");
510
		return (-1);
511
	}
512
513
	/*
514
	 * We need to pre-fetch the 3 possible strings we will look
515
	 * up to see what order they come in.  If the one without
516
	 * the -cur or -max comes in first then we ignore any later
517
	 * -cur or -max entries.
518
	 * Note that the cgetent routines will always return failure
519
	 * on the entry "".  This will cause our login_get* routines
520
	 * to use the default entry.
521
	 */
522
	if ((v = cgetcap(lc->lc_cap, name, '=')) != NULL) {
523
		if (v < cgetcap(lc->lc_cap, name_cur, '='))
524
			name_cur[0] = '\0';
525
		if (v < cgetcap(lc->lc_cap, name_max, '='))
526
			name_max[0] = '\0';
527
	}
528
529
#define	RCUR	r.rlim_cur
530
#define	RMAX	r.rlim_max
531
532
	switch (type) {
533
	case CTIME:
534
		RCUR = (rlim_t)login_getcaptime(lc, name, RCUR, RCUR);
535
		RMAX = (rlim_t)login_getcaptime(lc, name, RMAX, RMAX);
536
		rl.rlim_cur = (rlim_t)login_getcaptime(lc, name_cur, RCUR, RCUR);
537
		rl.rlim_max = (rlim_t)login_getcaptime(lc, name_max, RMAX, RMAX);
538
		break;
539
	case CSIZE:
540
		RCUR = (rlim_t)login_getcapsize(lc, name, RCUR, RCUR);
541
		RMAX = (rlim_t)login_getcapsize(lc, name, RMAX, RMAX);
542
		rl.rlim_cur = (rlim_t)login_getcapsize(lc, name_cur, RCUR, RCUR);
543
		rl.rlim_max = (rlim_t)login_getcapsize(lc, name_max, RMAX, RMAX);
544
		break;
545
	case CNUMB:
546
		RCUR = (rlim_t)login_getcapnum(lc, name, RCUR, RCUR);
547
		RMAX = (rlim_t)login_getcapnum(lc, name, RMAX, RMAX);
548
		rl.rlim_cur = (rlim_t)login_getcapnum(lc, name_cur, RCUR, RCUR);
549
		rl.rlim_max = (rlim_t)login_getcapnum(lc, name_max, RMAX, RMAX);
550
		break;
551
	default:
552
		return (-1);
553
	}
554
555
	if (setrlimit(what, &rl)) {
556
		syslog(LOG_ERR, "%s: setting resource limit %s: %m",
557
		    lc->lc_class, name);
558
		return (-1);
559
	}
560
#undef	RCUR
561
#undef	RMAX
562
	return (0);
563
}
564
565
int
566
setclasscontext(char *class, u_int flags)
567
{
568
	int ret;
569
	login_cap_t *lc;
570
571
	flags &= LOGIN_SETRESOURCES | LOGIN_SETPRIORITY | LOGIN_SETUMASK |
572
	    LOGIN_SETPATH;
573
574
	lc = login_getclass(class);
575
	ret = lc ? setusercontext(lc, NULL, 0, flags) : -1;
576
	login_close(lc);
577
	return (ret);
578
}
579
580
int
581
setusercontext(login_cap_t *lc, struct passwd *pwd, uid_t uid, u_int flags)
582
{
583
	login_cap_t *flc;
584
	quad_t p;
585
	int i;
586
587
	flc = NULL;
588
589
	if (!lc && !(flc = lc = login_getclass(pwd ? pwd->pw_class : NULL)))
590
		return (-1);
591
592
	/*
593
	 * Without the pwd entry being passed we cannot set either
594
	 * the group or the login.  We could complain about it.
595
	 */
596
	if (pwd == NULL)
597
		flags &= ~(LOGIN_SETGROUP|LOGIN_SETLOGIN);
598
599
	if (flags & LOGIN_SETRESOURCES)
600
		for (i = 0; r_list[i].name; ++i)
601
			if (gsetrl(lc, r_list[i].what, r_list[i].name,
602
			    r_list[i].type))
603
				/* XXX - call syslog()? */;
604
605
	if (flags & LOGIN_SETPRIORITY) {
606
		p = login_getcapnum(lc, "priority", 0, 0);
607
608
		if (setpriority(PRIO_PROCESS, 0, (int)p) < 0)
609
			syslog(LOG_ERR, "%s: setpriority: %m", lc->lc_class);
610
	}
611
612
	if (flags & LOGIN_SETUMASK) {
613
		p = login_getcapnum(lc, "umask", LOGIN_DEFUMASK,LOGIN_DEFUMASK);
614
		umask((mode_t)p);
615
	}
616
617
	if (flags & LOGIN_SETGROUP) {
618
		if (setresgid(pwd->pw_gid, pwd->pw_gid, pwd->pw_gid) < 0) {
619
			syslog(LOG_ERR, "setresgid(%u,%u,%u): %m",
620
			    pwd->pw_gid, pwd->pw_gid, pwd->pw_gid);
621
			login_close(flc);
622
			return (-1);
623
		}
624
625
		if (initgroups(pwd->pw_name, pwd->pw_gid) < 0) {
626
			syslog(LOG_ERR, "initgroups(%s,%u): %m",
627
			    pwd->pw_name, pwd->pw_gid);
628
			login_close(flc);
629
			return (-1);
630
		}
631
	}
632
633
	if (flags & LOGIN_SETLOGIN)
634
		if (setlogin(pwd->pw_name) < 0) {
635
			syslog(LOG_ERR, "setlogin(%s) failure: %m",
636
			    pwd->pw_name);
637
			login_close(flc);
638
			return (-1);
639
		}
640
641
	if (flags & LOGIN_SETUSER) {
642
		if (setresuid(uid, uid, uid) < 0) {
643
			syslog(LOG_ERR, "setresuid(%u,%u,%u): %m",
644
			    uid, uid, uid);
645
			login_close(flc);
646
			return (-1);
647
		}
648
	}
649
650
	if (flags & LOGIN_SETENV) {
651
		if (setuserenv(lc, pwd) == -1) {
652
			syslog(LOG_ERR, "could not set user environment: %m");
653
			login_close(flc);
654
			return (-1);
655
		}
656
	}
657
658
	if (flags & LOGIN_SETPATH) {
659
		if (setuserpath(lc, pwd) == -1) {
660
			syslog(LOG_ERR, "could not set PATH: %m");
661
			login_close(flc);
662
			return (-1);
663
		}
664
	}
665
666
	login_close(flc);
667
	return (0);
668
}
669
DEF_WEAK(setusercontext);
670
671
/*
672
 * Look up "path" for this user in login.conf and replace whitespace
673
 * with ':' while expanding '~' and '$'.  Sets the PATH environment
674
 * variable to the result or _PATH_DEFPATH on error.
675
 */
676
static int
677
setuserpath(login_cap_t *lc, const struct passwd *pwd)
678
{
679
	char *path = NULL, *opath = NULL, *op, *np;
680
	int len, error;
681
682
	if (lc->lc_cap == NULL)
683
		goto setit;		/* impossible */
684
685
	if ((len = cgetustr(lc->lc_cap, "path", &opath)) <= 0)
686
		goto setit;
687
688
	if ((path = malloc(len + 1)) == NULL)
689
		goto setit;
690
691
	/* Convert opath from space-separated to colon-separated path. */
692
	for (op = opath, np = path; *op != '\0'; ) {
693
		switch (*op) {
694
		case ' ':
695
		case '\t':
696
			/*
697
			 * Collapse consecutive spaces and trim any space
698
			 * at the very end.
699
			 */
700
			do {
701
				op++;
702
			} while (*op == ' ' || *op == '\t');
703
			if (*op != '\0')
704
				*np++ = ':';
705
			break;
706
		case '\\':
707
			/* check for escaped whitespace */
708
			if (*(op + 1) == ' ' || *(op + 1) == '\t')
709
				*np++ = *op++;
710
			/* FALLTHROUGH */
711
		default:
712
			*np++ = *op++;
713
			break;
714
		}
715
716
	}
717
	*np = '\0';
718
setit:
719
	error = login_setenv("PATH", path ? path : _PATH_DEFPATH, pwd, 1);
720
	free(opath);
721
	free(path);
722
	return (error);
723
}
724
725
/*
726
 * Look up "setenv" for this user in login.conf and set the comma-separated
727
 * list of environment variables, expanding '~' and '$'.
728
 */
729
static int
730
setuserenv(login_cap_t *lc, const struct passwd *pwd)
731
{
732
	char *beg, *end, *ep, *list, *value;
733
	int len, error;
734
735
	if (lc->lc_cap == NULL)
736
		return (-1);		/* impossible */
737
738
	if ((len = cgetustr(lc->lc_cap, "setenv", &list)) <= 0)
739
		return (0);
740
741
	for (beg = end = list, ep = list + len + 1; end < ep; end++) {
742
		switch (*end) {
743
		case '\\':
744
			if (*(end + 1) == ',')
745
				end++;	/* skip escaped comma */
746
			continue;
747
		case ',':
748
		case '\0':
749
			*end = '\0';
750
			if (beg == end) {
751
				beg++;
752
				continue;
753
			}
754
			break;
755
		default:
756
			continue;
757
		}
758
759
		if ((value = strchr(beg, '=')) != NULL)
760
			*value++ = '\0';
761
		else
762
			value = "";
763
		if ((error = login_setenv(beg, value, pwd, 0)) != 0) {
764
			free(list);
765
			return (error);
766
		}
767
		beg = end + 1;
768
	}
769
	free(list);
770
	return (0);
771
}
772
773
/*
774
 * Set an environment variable, substituting for ~ and $
775
 */
776
static int
777
login_setenv(char *name, char *ovalue, const struct passwd *pwd, int ispath)
778
{
779
	char *value = NULL;
780
	int error;
781
782
	if (*ovalue != '\0')
783
		value = expandstr(ovalue, pwd, ispath);
784
	error = setenv(name, value ? value : ovalue, 1);
785
	free(value);
786
	return (error);
787
}
788
789
/*
790
 * Convert an expression of the following forms
791
 * 	1) A number.
792
 *	2) A number followed by a b (mult by 512).
793
 *	3) A number followed by a k (mult by 1024).
794
 *	5) A number followed by a m (mult by 1024 * 1024).
795
 *	6) A number followed by a g (mult by 1024 * 1024 * 1024).
796
 *	7) A number followed by a t (mult by 1024 * 1024 * 1024 * 1024).
797
 *	8) Two or more numbers (with/without k,b,m,g, or t).
798
 *	   separated by x (also * for backwards compatibility), specifying
799
 *	   the product of the indicated values.
800
 */
801
static
802
u_quad_t
803
strtosize(char *str, char **endptr, int radix)
804
{
805
	u_quad_t num, num2;
806
	char *expr, *expr2;
807
808
	errno = 0;
809
	num = strtoull(str, &expr, radix);
810
	if (errno || expr == str) {
811
		if (endptr)
812
			*endptr = expr;
813
		return (num);
814
	}
815
816
	switch(*expr) {
817
	case 'b': case 'B':
818
		num = multiply(num, (u_quad_t)512);
819
		++expr;
820
		break;
821
	case 'k': case 'K':
822
		num = multiply(num, (u_quad_t)1024);
823
		++expr;
824
		break;
825
	case 'm': case 'M':
826
		num = multiply(num, (u_quad_t)1024 * 1024);
827
		++expr;
828
		break;
829
	case 'g': case 'G':
830
		num = multiply(num, (u_quad_t)1024 * 1024 * 1024);
831
		++expr;
832
		break;
833
	case 't': case 'T':
834
		num = multiply(num, (u_quad_t)1024 * 1024);
835
		num = multiply(num, (u_quad_t)1024 * 1024);
836
		++expr;
837
		break;
838
	}
839
840
	if (errno)
841
		goto erange;
842
843
	switch(*expr) {
844
	case '*':			/* Backward compatible. */
845
	case 'x':
846
		num2 = strtosize(expr+1, &expr2, radix);
847
		if (errno) {
848
			expr = expr2;
849
			goto erange;
850
		}
851
852
		if (expr2 == expr + 1) {
853
			if (endptr)
854
				*endptr = expr;
855
			return (num);
856
		}
857
		expr = expr2;
858
		num = multiply(num, num2);
859
		if (errno)
860
			goto erange;
861
		break;
862
	}
863
	if (endptr)
864
		*endptr = expr;
865
	return (num);
866
erange:
867
	if (endptr)
868
		*endptr = expr;
869
	errno = ERANGE;
870
	return (UQUAD_MAX);
871
}
872
873
static
874
u_quad_t
875
strtolimit(char *str, char **endptr, int radix)
876
{
877
	if (strcasecmp(str, "infinity") == 0 || strcasecmp(str, "inf") == 0) {
878
		if (endptr)
879
			*endptr = str + strlen(str);
880
		return ((u_quad_t)RLIM_INFINITY);
881
	}
882
	return (strtosize(str, endptr, radix));
883
}
884
885
static u_quad_t
886
multiply(u_quad_t n1, u_quad_t n2)
887
{
888
	static int bpw = 0;
889
	u_quad_t m;
890
	u_quad_t r;
891
	int b1, b2;
892
893
	/*
894
	 * Get rid of the simple cases
895
	 */
896
	if (n1 == 0 || n2 == 0)
897
		return (0);
898
	if (n1 == 1)
899
		return (n2);
900
	if (n2 == 1)
901
		return (n1);
902
903
	/*
904
	 * sizeof() returns number of bytes needed for storage.
905
	 * This may be different from the actual number of useful bits.
906
	 */
907
	if (!bpw) {
908
		bpw = sizeof(u_quad_t) * 8;
909
		while (((u_quad_t)1 << (bpw-1)) == 0)
910
			--bpw;
911
	}
912
913
	/*
914
	 * First check the magnitude of each number.  If the sum of the
915
	 * magnatude is way to high, reject the number.  (If this test
916
	 * is not done then the first multiply below may overflow.)
917
	 */
918
	for (b1 = bpw; (((u_quad_t)1 << (b1-1)) & n1) == 0; --b1)
919
		;
920
	for (b2 = bpw; (((u_quad_t)1 << (b2-1)) & n2) == 0; --b2)
921
		;
922
	if (b1 + b2 - 2 > bpw) {
923
		errno = ERANGE;
924
		return (UQUAD_MAX);
925
	}
926
927
	/*
928
	 * Decompose the multiplication to be:
929
	 * h1 = n1 & ~1
930
	 * h2 = n2 & ~1
931
	 * l1 = n1 & 1
932
	 * l2 = n2 & 1
933
	 * (h1 + l1) * (h2 + l2)
934
	 * (h1 * h2) + (h1 * l2) + (l1 * h2) + (l1 * l2)
935
	 *
936
	 * Since h1 && h2 do not have the low bit set, we can then say:
937
	 *
938
	 * (h1>>1 * h2>>1 * 4) + ...
939
	 *
940
	 * So if (h1>>1 * h2>>1) > (1<<(bpw - 2)) then the result will
941
	 * overflow.
942
	 *
943
	 * Finally, if MAX - ((h1 * l2) + (l1 * h2) + (l1 * l2)) < (h1*h2)
944
	 * then adding in residual amount will cause an overflow.
945
	 */
946
947
	m = (n1 >> 1) * (n2 >> 1);
948
949
	if (m >= ((u_quad_t)1 << (bpw-2))) {
950
		errno = ERANGE;
951
		return (UQUAD_MAX);
952
	}
953
954
	m *= 4;
955
956
	r = (n1 & n2 & 1)
957
	  + (n2 & 1) * (n1 & ~(u_quad_t)1)
958
	  + (n1 & 1) * (n2 & ~(u_quad_t)1);
959
960
	if ((u_quad_t)(m + r) < m) {
961
		errno = ERANGE;
962
		return (UQUAD_MAX);
963
	}
964
	m += r;
965
966
	return (m);
967
}
968
969
int
970
secure_path(char *path)
971
{
972
	struct stat sb;
973
974
	/*
975
	 * If not a regular file, or is owned/writeable by someone
976
	 * other than root, quit.
977
	 */
978
	if (lstat(path, &sb) < 0) {
979
		syslog(LOG_ERR, "cannot stat %s: %m", path);
980
		return (-1);
981
	} else if (!S_ISREG(sb.st_mode)) {
982
		syslog(LOG_ERR, "%s: not a regular file", path);
983
		return (-1);
984
	} else if (sb.st_uid != 0) {
985
		syslog(LOG_ERR, "%s: not owned by root", path);
986
		return (-1);
987
	} else if (sb.st_mode & (S_IWGRP | S_IWOTH)) {
988
		syslog(LOG_ERR, "%s: writable by non-root", path);
989
		return (-1);
990
	}
991
	return (0);
992
}
993
DEF_WEAK(secure_path);
994
995
/*
996
 * Check whether or not a tilde in a string should be expanded.
997
 * We only do expansion for things like "~", "~/...", ~me", "~me/...".
998
 * Additionally, for paths the tilde must be a the beginning.
999
 */
1000
#define tilde_valid(s, b, u, l, ip) \
1001
    ((!(ip) || (s) == (b) || (s)[-1] == ':') && \
1002
    ((s)[1] == '/' || (s)[1] == '\0' || \
1003
    (strncmp((s)+1, u, l) == 0 && ((s)[l+1] == '/' || (s)[l+1] == '\0'))))
1004
1005
/*
1006
 * Make a copy of a string, expanding '~' to the user's homedir, '$' to the
1007
 * login name and other escape sequences as per cgetstr(3).
1008
 */
1009
static char *
1010
expandstr(const char *ostr, const struct passwd *pwd, int ispath)
1011
{
1012
	size_t n, olen, nlen, ulen, dlen;
1013
	const char *ep, *eo, *op;
1014
	char *nstr, *np;
1015
	int ch;
1016
1017
	if (pwd != NULL) {
1018
		ulen = strlen(pwd->pw_name);
1019
		dlen = strlen(pwd->pw_dir);
1020
	}
1021
1022
	/* calculate the size of the new string */
1023
	olen = nlen = strlen(ostr);
1024
	for (op = ostr, ep = ostr + olen; op < ep; op++) {
1025
		switch (*op) {
1026
		case '~':
1027
			if (pwd == NULL ||
1028
			    !tilde_valid(op, ostr, pwd->pw_name, ulen, ispath))
1029
				break;
1030
			if (op[1] != '/' && op[1] != '\0') {
1031
				op += ulen;	/* ~username */
1032
				nlen = nlen - ulen - 1 + dlen;
1033
			} else
1034
				nlen += dlen - 1;
1035
			break;
1036
		case '$':
1037
			if (pwd != NULL)
1038
				nlen += ulen - 1;
1039
			break;
1040
		case '^':
1041
			/* control char */
1042
			if (*++op != '\0')
1043
				nlen--;
1044
			break;
1045
		case '\\':
1046
			if (op[1] == '\0')
1047
				break;
1048
			/*
1049
			 * Byte in octal notation (\123) or an escaped char (\t)
1050
			 */
1051
			eo = op + 4;
1052
			do {
1053
				op++;
1054
				nlen--;
1055
			} while (op < eo && *op >= '0' && *op <= '7');
1056
			break;
1057
		}
1058
	}
1059
	if ((np = nstr = malloc(++nlen)) == NULL)
1060
		return (NULL);
1061
1062
	for (op = ostr, ep = ostr + olen; op < ep; op++) {
1063
		switch ((ch = *op)) {
1064
		case '~':
1065
			if (pwd == NULL ||
1066
			    !tilde_valid(op, ostr, pwd->pw_name, ulen, ispath))
1067
				break;
1068
			if (op[1] != '/' && op[1] != '\0')
1069
				op += ulen;	/* ~username */
1070
			strlcpy(np, pwd->pw_dir, nlen);
1071
			nlen -= dlen;
1072
			np += dlen;
1073
			continue;
1074
		case '$':
1075
			if (pwd == NULL)
1076
				break;
1077
			strlcpy(np, pwd->pw_name, nlen);
1078
			nlen -= ulen;
1079
			np += ulen;
1080
			continue;
1081
		case '^':
1082
			if (op[1] != '\0')
1083
				ch = *++op & 037;
1084
			break;
1085
		case '\\':
1086
			if (op[1] == '\0')
1087
				break;
1088
			switch(*++op) {
1089
			case '0': case '1': case '2': case '3':
1090
			case '4': case '5': case '6': case '7':
1091
				/* byte in octal up to 3 digits long */
1092
				ch = 0;
1093
				n = 3;
1094
				do {
1095
					ch = ch * 8 + (*op++ - '0');
1096
				} while (--n && *op >= '0' && *op <= '7');
1097
				break;
1098
			case 'b': case 'B':
1099
				ch = '\b';
1100
				break;
1101
			case 't': case 'T':
1102
				ch = '\t';
1103
				break;
1104
			case 'n': case 'N':
1105
				ch = '\n';
1106
				break;
1107
			case 'f': case 'F':
1108
				ch = '\f';
1109
				break;
1110
			case 'r': case 'R':
1111
				ch = '\r';
1112
				break;
1113
			case 'e': case 'E':
1114
				ch = '\033';
1115
				break;
1116
			case 'c': case 'C':
1117
				ch = ':';
1118
				break;
1119
			default:
1120
				ch = *op;
1121
				break;
1122
			}
1123
			break;
1124
		}
1125
		*np++ = ch;
1126
		nlen--;
1127
	}
1128
	*np = '\0';
1129
	return (nstr);
1130
}