1 /*
2  * Zebra privileges.
3  *
4  * Copyright (C) 2003 Paul Jakma.
5  * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
6  *
7  * This file is part of GNU Zebra.
8  *
9  * GNU Zebra is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU General Public License as published by the
11  * Free Software Foundation; either version 2, or (at your option) any
12  * later version.
13  *
14  * GNU Zebra is distributed in the hope that it will be useful, but
15  * WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License along
20  * with this program; see the file COPYING; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
22  */
23 #include <zebra.h>
24 #include "log.h"
25 #include "privs.h"
26 #include "memory.h"
27 #include "frr_pthread.h"
28 #include "lib_errors.h"
29 #include "lib/queue.h"
30 
31 DEFINE_MTYPE_STATIC(LIB, PRIVS, "Privilege information")
32 
33 /*
34  * Different capabilities/privileges apis have different characteristics: some
35  * are process-wide, and some are per-thread.
36  */
37 #ifdef HAVE_CAPABILITIES
38 #ifdef HAVE_LCAPS
39 static const bool privs_per_process;  /* = false */
40 #elif defined(HAVE_SOLARIS_CAPABILITIES)
41 static const bool privs_per_process = true;
42 #endif
43 #else
44 static const bool privs_per_process = true;
45 #endif	/* HAVE_CAPABILITIES */
46 
47 #ifdef HAVE_CAPABILITIES
48 
49 /* sort out some generic internal types for:
50  *
51  * privilege values (cap_value_t, priv_t) 	-> pvalue_t
52  * privilege set (..., priv_set_t) 		-> pset_t
53  * privilege working storage (cap_t, ...) 	-> pstorage_t
54  *
55  * values we think of as numeric (they're ints really, but we dont know)
56  * sets are mostly opaque, to hold a set of privileges, related in some way.
57  * storage binds together a set of sets we're interested in.
58  * (in reality: cap_value_t and priv_t are ints)
59  */
60 #ifdef HAVE_LCAPS
61 /* Linux doesn't have a 'set' type: a set of related privileges */
62 struct _pset {
63 	int num;
64 	cap_value_t *caps;
65 };
66 typedef cap_value_t pvalue_t;
67 typedef struct _pset pset_t;
68 typedef cap_t pstorage_t;
69 
70 #elif defined(HAVE_SOLARIS_CAPABILITIES)
71 typedef priv_t pvalue_t;
72 typedef priv_set_t pset_t;
73 typedef priv_set_t *pstorage_t;
74 #else /* neither LCAPS nor SOLARIS_CAPABILITIES */
75 #error "HAVE_CAPABILITIES defined, but neither LCAPS nor Solaris Capabilties!"
76 #endif /* HAVE_LCAPS */
77 #endif /* HAVE_CAPABILITIES */
78 
79 /* the default NULL state we report is RAISED, but could be LOWERED if
80  * zprivs_terminate is called and the NULL handler is installed.
81  */
82 static zebra_privs_current_t zprivs_null_state = ZPRIVS_RAISED;
83 
84 /* internal privileges state */
85 static struct _zprivs_t {
86 #ifdef HAVE_CAPABILITIES
87 	pstorage_t caps;   /* working storage        */
88 	pset_t *syscaps_p; /* system-type requested permitted caps    */
89 	pset_t *syscaps_i; /* system-type requested inheritable caps  */
90 #endif			   /* HAVE_CAPABILITIES */
91 	uid_t zuid,	/* uid to run as            */
92 		zsuid;     /* saved uid                */
93 	gid_t zgid;	/* gid to run as            */
94 	gid_t vtygrp;      /* gid for vty sockets      */
95 } zprivs_state;
96 
97 /* externally exported but not directly accessed functions */
98 #ifdef HAVE_CAPABILITIES
99 int zprivs_change_caps(zebra_privs_ops_t);
100 zebra_privs_current_t zprivs_state_caps(void);
101 #endif /* HAVE_CAPABILITIES */
102 int zprivs_change_uid(zebra_privs_ops_t);
103 zebra_privs_current_t zprivs_state_uid(void);
104 int zprivs_change_null(zebra_privs_ops_t);
105 zebra_privs_current_t zprivs_state_null(void);
106 
107 #ifdef HAVE_CAPABILITIES
108 /* internal capability API */
109 static pset_t *zcaps2sys(zebra_capabilities_t *, int);
110 static void zprivs_caps_init(struct zebra_privs_t *);
111 static void zprivs_caps_terminate(void);
112 
113 /* Map of Quagga abstract capabilities to system capabilities */
114 static struct {
115 	int num;
116 	pvalue_t *system_caps;
117 } cap_map[ZCAP_MAX] = {
118 #ifdef HAVE_LCAPS /* Quagga -> Linux capabilities mappings */
119 		[ZCAP_SETID] =
120 			{
121 				2, (pvalue_t[]){CAP_SETGID, CAP_SETUID},
122 			},
123 		[ZCAP_BIND] =
124 			{
125 				1, (pvalue_t[]){CAP_NET_BIND_SERVICE},
126 			},
127 		[ZCAP_NET_ADMIN] =
128 			{
129 				1, (pvalue_t[]){CAP_NET_ADMIN},
130 			},
131 		[ZCAP_NET_RAW] =
132 			{
133 				1, (pvalue_t[]){CAP_NET_RAW},
134 			},
135 		[ZCAP_CHROOT] =
136 			{
137 				1,
138 				(pvalue_t[]){
139 					CAP_SYS_CHROOT,
140 				},
141 			},
142 		[ZCAP_NICE] =
143 			{
144 				1, (pvalue_t[]){CAP_SYS_NICE},
145 			},
146 		[ZCAP_PTRACE] =
147 			{
148 				1, (pvalue_t[]){CAP_SYS_PTRACE},
149 			},
150 		[ZCAP_DAC_OVERRIDE] =
151 			{
152 				1, (pvalue_t[]){CAP_DAC_OVERRIDE},
153 			},
154 		[ZCAP_READ_SEARCH] =
155 			{
156 				1, (pvalue_t[]){CAP_DAC_READ_SEARCH},
157 			},
158 		[ZCAP_SYS_ADMIN] =
159 			{
160 				1, (pvalue_t[]){CAP_SYS_ADMIN},
161 			},
162 		[ZCAP_FOWNER] =
163 			{
164 				1, (pvalue_t[]){CAP_FOWNER},
165 			},
166 #elif defined(HAVE_SOLARIS_CAPABILITIES) /* HAVE_LCAPS */
167 		/* Quagga -> Solaris privilege mappings */
168 		[ZCAP_SETID] =
169 			{
170 				1, (pvalue_t[]){PRIV_PROC_SETID},
171 			},
172 		[ZCAP_BIND] =
173 			{
174 				1, (pvalue_t[]){PRIV_NET_PRIVADDR},
175 			},
176 /* IP_CONFIG is a subset of NET_CONFIG and is allowed in zones */
177 #ifdef PRIV_SYS_IP_CONFIG
178 		[ZCAP_NET_ADMIN] =
179 			{
180 				1, (pvalue_t[]){PRIV_SYS_IP_CONFIG},
181 			},
182 #else
183 		[ZCAP_NET_ADMIN] =
184 			{
185 				1, (pvalue_t[]){PRIV_SYS_NET_CONFIG},
186 			},
187 #endif
188 		[ZCAP_NET_RAW] =
189 			{
190 				2, (pvalue_t[]){PRIV_NET_RAWACCESS,
191 						PRIV_NET_ICMPACCESS},
192 			},
193 		[ZCAP_CHROOT] =
194 			{
195 				1, (pvalue_t[]){PRIV_PROC_CHROOT},
196 			},
197 		[ZCAP_NICE] =
198 			{
199 				1, (pvalue_t[]){PRIV_PROC_PRIOCNTL},
200 			},
201 		[ZCAP_PTRACE] =
202 			{
203 				1, (pvalue_t[]){PRIV_PROC_SESSION},
204 			},
205 		[ZCAP_DAC_OVERRIDE] =
206 			{
207 				5, (pvalue_t[]){PRIV_FILE_DAC_EXECUTE,
208 						PRIV_FILE_DAC_READ,
209 						PRIV_FILE_DAC_SEARCH,
210 						PRIV_FILE_DAC_WRITE,
211 						PRIV_FILE_DAC_SEARCH},
212 			},
213 		[ZCAP_READ_SEARCH] =
214 			{
215 				2, (pvalue_t[]){PRIV_FILE_DAC_SEARCH,
216 						PRIV_FILE_DAC_READ},
217 			},
218 		[ZCAP_SYS_ADMIN] =
219 			{
220 				1, (pvalue_t[]){PRIV_SYS_ADMIN},
221 			},
222 		[ZCAP_FOWNER] =
223 			{
224 				1, (pvalue_t[]){PRIV_FILE_OWNER},
225 			},
226 #endif /* HAVE_SOLARIS_CAPABILITIES */
227 };
228 
229 #ifdef HAVE_LCAPS
230 /* Linux forms of capabilities methods */
231 /* convert zebras privileges to system capabilities */
zcaps2sys(zebra_capabilities_t * zcaps,int num)232 static pset_t *zcaps2sys(zebra_capabilities_t *zcaps, int num)
233 {
234 	pset_t *syscaps;
235 	int i, j = 0, count = 0;
236 
237 	if (!num)
238 		return NULL;
239 
240 	/* first count up how many system caps we have */
241 	for (i = 0; i < num; i++)
242 		count += cap_map[zcaps[i]].num;
243 
244 	if ((syscaps = XCALLOC(MTYPE_PRIVS, (sizeof(pset_t) * num))) == NULL) {
245 		fprintf(stderr, "%s: could not allocate syscaps!", __func__);
246 		return NULL;
247 	}
248 
249 	syscaps->caps = XCALLOC(MTYPE_PRIVS, (sizeof(pvalue_t) * count));
250 
251 	if (!syscaps->caps) {
252 		fprintf(stderr, "%s: could not XCALLOC caps!", __func__);
253 		return NULL;
254 	}
255 
256 	/* copy the capabilities over */
257 	count = 0;
258 	for (i = 0; i < num; i++)
259 		for (j = 0; j < cap_map[zcaps[i]].num; j++)
260 			syscaps->caps[count++] =
261 				cap_map[zcaps[i]].system_caps[j];
262 
263 	/* iterations above should be exact same as previous count, obviously..
264 	 */
265 	syscaps->num = count;
266 
267 	return syscaps;
268 }
269 
270 /* set or clear the effective capabilities to/from permitted */
zprivs_change_caps(zebra_privs_ops_t op)271 int zprivs_change_caps(zebra_privs_ops_t op)
272 {
273 	cap_flag_value_t cflag;
274 
275 	/* should be no possibility of being called without valid caps */
276 	assert(zprivs_state.syscaps_p && zprivs_state.caps);
277 	if (!(zprivs_state.syscaps_p && zprivs_state.caps))
278 		exit(1);
279 
280 	if (op == ZPRIVS_RAISE)
281 		cflag = CAP_SET;
282 	else if (op == ZPRIVS_LOWER)
283 		cflag = CAP_CLEAR;
284 	else
285 		return -1;
286 
287 	if (!cap_set_flag(zprivs_state.caps, CAP_EFFECTIVE,
288 			  zprivs_state.syscaps_p->num,
289 			  zprivs_state.syscaps_p->caps, cflag))
290 		return cap_set_proc(zprivs_state.caps);
291 	return -1;
292 }
293 
zprivs_state_caps(void)294 zebra_privs_current_t zprivs_state_caps(void)
295 {
296 	int i;
297 	cap_flag_value_t val;
298 
299 	/* should be no possibility of being called without valid caps */
300 	assert(zprivs_state.syscaps_p && zprivs_state.caps);
301 	if (!(zprivs_state.syscaps_p && zprivs_state.caps))
302 		exit(1);
303 
304 	for (i = 0; i < zprivs_state.syscaps_p->num; i++) {
305 		if (cap_get_flag(zprivs_state.caps,
306 				 zprivs_state.syscaps_p->caps[i], CAP_EFFECTIVE,
307 				 &val)) {
308 			flog_err(
309 				EC_LIB_SYSTEM_CALL,
310 				"zprivs_state_caps: could not cap_get_flag, %s",
311 				safe_strerror(errno));
312 			return ZPRIVS_UNKNOWN;
313 		}
314 		if (val == CAP_SET)
315 			return ZPRIVS_RAISED;
316 	}
317 	return ZPRIVS_LOWERED;
318 }
319 
zprivs_caps_init(struct zebra_privs_t * zprivs)320 static void zprivs_caps_init(struct zebra_privs_t *zprivs)
321 {
322 	zprivs_state.syscaps_p = zcaps2sys(zprivs->caps_p, zprivs->cap_num_p);
323 	zprivs_state.syscaps_i = zcaps2sys(zprivs->caps_i, zprivs->cap_num_i);
324 
325 	/* Tell kernel we want caps maintained across uid changes */
326 	if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
327 		fprintf(stderr,
328 			"privs_init: could not set PR_SET_KEEPCAPS, %s\n",
329 			safe_strerror(errno));
330 		exit(1);
331 	}
332 
333 	/* we have caps, we have no need to ever change back the original user
334 	 */
335 	/* only change uid if we don't have the correct one */
336 	if ((zprivs_state.zuid) && (zprivs_state.zsuid != zprivs_state.zuid)) {
337 		if (setreuid(zprivs_state.zuid, zprivs_state.zuid)) {
338 			fprintf(stderr,
339 				"zprivs_init (cap): could not setreuid, %s\n",
340 				safe_strerror(errno));
341 			exit(1);
342 		}
343 	}
344 
345 	if (!zprivs_state.syscaps_p)
346 		return;
347 
348 	if (!(zprivs_state.caps = cap_init())) {
349 		fprintf(stderr, "privs_init: failed to cap_init, %s\n",
350 			safe_strerror(errno));
351 		exit(1);
352 	}
353 
354 	if (cap_clear(zprivs_state.caps)) {
355 		fprintf(stderr, "privs_init: failed to cap_clear, %s\n",
356 			safe_strerror(errno));
357 		exit(1);
358 	}
359 
360 	/* set permitted caps */
361 	cap_set_flag(zprivs_state.caps, CAP_PERMITTED,
362 		     zprivs_state.syscaps_p->num, zprivs_state.syscaps_p->caps,
363 		     CAP_SET);
364 
365 	/* set inheritable caps, if any */
366 	if (zprivs_state.syscaps_i && zprivs_state.syscaps_i->num) {
367 		cap_set_flag(zprivs_state.caps, CAP_INHERITABLE,
368 			     zprivs_state.syscaps_i->num,
369 			     zprivs_state.syscaps_i->caps, CAP_SET);
370 	}
371 
372 	/* apply caps. CAP_EFFECTIVE is cleared. we'll raise the caps as
373 	 * and when, and only when, they are needed.
374 	 */
375 	if (cap_set_proc(zprivs_state.caps)) {
376 		cap_t current_caps;
377 		char *current_caps_text = NULL;
378 		char *wanted_caps_text = NULL;
379 
380 		fprintf(stderr, "privs_init: initial cap_set_proc failed: %s\n",
381 			safe_strerror(errno));
382 
383 		current_caps = cap_get_proc();
384 		if (current_caps) {
385 			current_caps_text = cap_to_text(current_caps, NULL);
386 			cap_free(current_caps);
387 		}
388 
389 		wanted_caps_text = cap_to_text(zprivs_state.caps, NULL);
390 		fprintf(stderr, "Wanted caps: %s\n",
391 			wanted_caps_text ? wanted_caps_text : "???");
392 		fprintf(stderr, "Have   caps: %s\n",
393 			current_caps_text ? current_caps_text : "???");
394 		if (current_caps_text)
395 			cap_free(current_caps_text);
396 		if (wanted_caps_text)
397 			cap_free(wanted_caps_text);
398 
399 		exit(1);
400 	}
401 
402 	/* set methods for the caller to use */
403 	zprivs->change = zprivs_change_caps;
404 	zprivs->current_state = zprivs_state_caps;
405 }
406 
zprivs_caps_terminate(void)407 static void zprivs_caps_terminate(void)
408 {
409 	/* Clear all capabilities, if we have any. */
410 	if (zprivs_state.caps)
411 		cap_clear(zprivs_state.caps);
412 	else
413 		return;
414 
415 	/* and boom, capabilities are gone forever */
416 	if (cap_set_proc(zprivs_state.caps)) {
417 		fprintf(stderr, "privs_terminate: cap_set_proc failed, %s",
418 			safe_strerror(errno));
419 		exit(1);
420 	}
421 
422 	/* free up private state */
423 	if (zprivs_state.syscaps_p->num) {
424 		XFREE(MTYPE_PRIVS, zprivs_state.syscaps_p->caps);
425 		XFREE(MTYPE_PRIVS, zprivs_state.syscaps_p);
426 	}
427 
428 	if (zprivs_state.syscaps_i && zprivs_state.syscaps_i->num) {
429 		XFREE(MTYPE_PRIVS, zprivs_state.syscaps_i->caps);
430 		XFREE(MTYPE_PRIVS, zprivs_state.syscaps_i);
431 	}
432 
433 	cap_free(zprivs_state.caps);
434 }
435 #elif defined(HAVE_SOLARIS_CAPABILITIES) /* !HAVE_LCAPS */
436 
437 /* Solaris specific capability/privilege methods
438  *
439  * Resources:
440  * - the 'privileges' man page
441  * - http://cvs.opensolaris.org
442  * -
443  * http://blogs.sun.com/roller/page/gbrunett?entry=privilege_enabling_set_id_programs1
444  */
445 
zprivs_caps_minimal()446 static pset_t *zprivs_caps_minimal()
447 {
448 	pset_t *minimal;
449 
450 	if ((minimal = priv_str_to_set("basic", ",", NULL)) == NULL) {
451 		fprintf(stderr, "%s: couldn't get basic set!\n", __func__);
452 		exit(1);
453 	}
454 
455 	/* create a minimal privilege set from the basic set */
456 	(void)priv_delset(minimal, PRIV_PROC_EXEC);
457 	(void)priv_delset(minimal, PRIV_PROC_INFO);
458 	(void)priv_delset(minimal, PRIV_PROC_SESSION);
459 	(void)priv_delset(minimal, PRIV_FILE_LINK_ANY);
460 
461 	return minimal;
462 }
463 
464 /* convert zebras privileges to system capabilities */
zcaps2sys(zebra_capabilities_t * zcaps,int num)465 static pset_t *zcaps2sys(zebra_capabilities_t *zcaps, int num)
466 {
467 	pset_t *syscaps;
468 	int i, j = 0;
469 
470 	if ((syscaps = priv_allocset()) == NULL) {
471 		fprintf(stderr, "%s: could not allocate syscaps!\n", __func__);
472 		exit(1);
473 	}
474 
475 	priv_emptyset(syscaps);
476 
477 	for (i = 0; i < num; i++)
478 		for (j = 0; j < cap_map[zcaps[i]].num; j++)
479 			priv_addset(syscaps, cap_map[zcaps[i]].system_caps[j]);
480 
481 	return syscaps;
482 }
483 
484 /* callback exported to users to RAISE and LOWER effective privileges
485  * from nothing to the given permitted set and back down
486  */
zprivs_change_caps(zebra_privs_ops_t op)487 int zprivs_change_caps(zebra_privs_ops_t op)
488 {
489 	pset_t *privset;
490 
491 	/* should be no possibility of being called without valid caps */
492 	assert(zprivs_state.syscaps_p);
493 	if (!zprivs_state.syscaps_p) {
494 		fprintf(stderr, "%s: Eek, missing privileged caps!", __func__);
495 		exit(1);
496 	}
497 
498 	assert(zprivs_state.caps);
499 	if (!zprivs_state.caps) {
500 		fprintf(stderr, "%s: Eek, missing caps!", __func__);
501 		exit(1);
502 	}
503 
504 	/* to raise: copy original permitted as our working effective set
505 	 * to lower: copy regular effective set stored in zprivs_state.caps
506 	 */
507 	if (op == ZPRIVS_RAISE)
508 		privset = zprivs_state.syscaps_p;
509 	else if (op == ZPRIVS_LOWER)
510 		privset = zprivs_state.caps;
511 	else
512 		return -1;
513 
514 	if (setppriv(PRIV_SET, PRIV_EFFECTIVE, privset) != 0)
515 		return -1;
516 
517 	return 0;
518 }
519 
520 /* Retrieve current privilege state, is it RAISED or LOWERED? */
zprivs_state_caps(void)521 zebra_privs_current_t zprivs_state_caps(void)
522 {
523 	zebra_privs_current_t result;
524 	pset_t *effective;
525 
526 	if ((effective = priv_allocset()) == NULL) {
527 		fprintf(stderr, "%s: failed to get priv_allocset! %s\n",
528 			__func__, safe_strerror(errno));
529 		return ZPRIVS_UNKNOWN;
530 	}
531 
532 	if (getppriv(PRIV_EFFECTIVE, effective)) {
533 		fprintf(stderr, "%s: failed to get state! %s\n", __func__,
534 			safe_strerror(errno));
535 		result = ZPRIVS_UNKNOWN;
536 	} else {
537 		if (priv_isequalset(effective, zprivs_state.syscaps_p))
538 			result = ZPRIVS_RAISED;
539 		else if (priv_isequalset(effective, zprivs_state.caps))
540 			result = ZPRIVS_LOWERED;
541 		else
542 			result = ZPRIVS_UNKNOWN;
543 	}
544 
545 	priv_freeset(effective);
546 	return result;
547 }
548 
zprivs_caps_init(struct zebra_privs_t * zprivs)549 static void zprivs_caps_init(struct zebra_privs_t *zprivs)
550 {
551 	pset_t *basic;
552 	pset_t *minimal;
553 
554 	/* the specified sets */
555 	zprivs_state.syscaps_p = zcaps2sys(zprivs->caps_p, zprivs->cap_num_p);
556 	zprivs_state.syscaps_i = zcaps2sys(zprivs->caps_i, zprivs->cap_num_i);
557 
558 	/* nonsensical to have gotten here but not have capabilities */
559 	if (!zprivs_state.syscaps_p) {
560 		fprintf(stderr,
561 			"%s: capabilities enabled, but no valid capabilities supplied\n",
562 			__func__);
563 	}
564 
565 	/* We retain the basic set in our permitted set, as Linux has no
566 	 * equivalent. The basic set on Linux hence is implicit, always
567 	 * there.
568 	 */
569 	if ((basic = priv_str_to_set("basic", ",", NULL)) == NULL) {
570 		fprintf(stderr, "%s: couldn't get basic set!\n", __func__);
571 		exit(1);
572 	}
573 
574 	/* Add the basic set to the permitted set */
575 	priv_union(basic, zprivs_state.syscaps_p);
576 	priv_freeset(basic);
577 
578 	/* Hey kernel, we know about privileges!
579 	 * this isn't strictly required, use of setppriv should have same effect
580 	 */
581 	if (setpflags(PRIV_AWARE, 1)) {
582 		fprintf(stderr, "%s: error setting PRIV_AWARE!, %s\n", __func__,
583 			safe_strerror(errno));
584 		exit(1);
585 	}
586 
587 	/* need either valid or empty sets for both p and i.. */
588 	assert(zprivs_state.syscaps_i && zprivs_state.syscaps_p);
589 
590 	/* we have caps, we have no need to ever change back the original user
591 	 * change real, effective and saved to the specified user.
592 	 */
593 	/* only change uid if we don't have the correct one */
594 	if ((zprivs_state.zuid) && (zprivs_state.zsuid != zprivs_state.zuid)) {
595 		if (setreuid(zprivs_state.zuid, zprivs_state.zuid)) {
596 			fprintf(stderr, "%s: could not setreuid, %s\n",
597 				__func__, safe_strerror(errno));
598 			exit(1);
599 		}
600 	}
601 
602 	/* set the permitted set */
603 	if (setppriv(PRIV_SET, PRIV_PERMITTED, zprivs_state.syscaps_p)) {
604 		fprintf(stderr, "%s: error setting permitted set!, %s\n",
605 			__func__, safe_strerror(errno));
606 		exit(1);
607 	}
608 
609 	/* set the inheritable set */
610 	if (setppriv(PRIV_SET, PRIV_INHERITABLE, zprivs_state.syscaps_i)) {
611 		fprintf(stderr, "%s: error setting inheritable set!, %s\n",
612 			__func__, safe_strerror(errno));
613 		exit(1);
614 	}
615 
616 	/* we need a minimal basic set for 'effective', potentially for
617 	 * inheritable too */
618 	minimal = zprivs_caps_minimal();
619 
620 	/* now set the effective set with a subset of basic privileges */
621 	if (setppriv(PRIV_SET, PRIV_EFFECTIVE, minimal)) {
622 		fprintf(stderr, "%s: error setting effective set!, %s\n",
623 			__func__, safe_strerror(errno));
624 		exit(1);
625 	}
626 
627 	/* we'll use the minimal set as our working-storage privset */
628 	zprivs_state.caps = minimal;
629 
630 	/* set methods for the caller to use */
631 	zprivs->change = zprivs_change_caps;
632 	zprivs->current_state = zprivs_state_caps;
633 }
634 
zprivs_caps_terminate(void)635 static void zprivs_caps_terminate(void)
636 {
637 	assert(zprivs_state.caps);
638 
639 	/* clear all capabilities by using working-storage privset */
640 	setppriv(PRIV_SET, PRIV_EFFECTIVE, zprivs_state.caps);
641 	setppriv(PRIV_SET, PRIV_PERMITTED, zprivs_state.caps);
642 	setppriv(PRIV_SET, PRIV_INHERITABLE, zprivs_state.caps);
643 
644 	/* free up private state */
645 	if (zprivs_state.syscaps_p)
646 		priv_freeset(zprivs_state.syscaps_p);
647 	if (zprivs_state.syscaps_i)
648 		priv_freeset(zprivs_state.syscaps_i);
649 
650 	priv_freeset(zprivs_state.caps);
651 }
652 #else /* !HAVE_LCAPS && ! HAVE_SOLARIS_CAPABILITIES */
653 #error "Neither Solaris nor Linux capabilities, dazed and confused..."
654 #endif /* HAVE_LCAPS */
655 #endif /* HAVE_CAPABILITIES */
656 
zprivs_change_uid(zebra_privs_ops_t op)657 int zprivs_change_uid(zebra_privs_ops_t op)
658 {
659 	if (zprivs_state.zsuid == zprivs_state.zuid)
660 		return 0;
661 	if (op == ZPRIVS_RAISE)
662 		return seteuid(zprivs_state.zsuid);
663 	else if (op == ZPRIVS_LOWER)
664 		return seteuid(zprivs_state.zuid);
665 	else
666 		return -1;
667 }
668 
zprivs_state_uid(void)669 zebra_privs_current_t zprivs_state_uid(void)
670 {
671 	return ((zprivs_state.zuid == geteuid()) ? ZPRIVS_LOWERED
672 						 : ZPRIVS_RAISED);
673 }
674 
zprivs_change_null(zebra_privs_ops_t op)675 int zprivs_change_null(zebra_privs_ops_t op)
676 {
677 	return 0;
678 }
679 
zprivs_state_null(void)680 zebra_privs_current_t zprivs_state_null(void)
681 {
682 	return zprivs_null_state;
683 }
684 
685 #ifndef HAVE_GETGROUPLIST
686 /* Solaris 11 has no getgrouplist() */
getgrouplist(const char * user,gid_t group,gid_t * groups,int * ngroups)687 static int getgrouplist(const char *user, gid_t group, gid_t *groups,
688 			int *ngroups)
689 {
690 	struct group *grp;
691 	size_t usridx;
692 	int pos = 0, ret;
693 
694 	if (pos < *ngroups)
695 		groups[pos] = group;
696 	pos++;
697 
698 	setgrent();
699 	while ((grp = getgrent())) {
700 		if (grp->gr_gid == group)
701 			continue;
702 		for (usridx = 0; grp->gr_mem[usridx] != NULL; usridx++)
703 			if (!strcmp(grp->gr_mem[usridx], user)) {
704 				if (pos < *ngroups)
705 					groups[pos] = grp->gr_gid;
706 				pos++;
707 				break;
708 			}
709 	}
710 	endgrent();
711 
712 	ret = (pos <= *ngroups) ? pos : -1;
713 	*ngroups = pos;
714 	return ret;
715 }
716 #endif /* HAVE_GETGROUPLIST */
717 
718 /*
719  * Helper function that locates a refcounting object to use: a process-wide
720  * object or a per-pthread object.
721  */
get_privs_refs(struct zebra_privs_t * privs)722 static struct zebra_privs_refs_t *get_privs_refs(struct zebra_privs_t *privs)
723 {
724 	struct zebra_privs_refs_t *temp, *refs = NULL;
725 	pthread_t tid;
726 
727 	if (privs_per_process)
728 		refs = &(privs->process_refs);
729 	else {
730 		/* Locate - or create - the object for the current pthread. */
731 		tid = pthread_self();
732 
733 		STAILQ_FOREACH(temp, &(privs->thread_refs), entry) {
734 			if (pthread_equal(temp->tid, tid)) {
735 				refs = temp;
736 				break;
737 			}
738 		}
739 
740 		/* Need to create a new refcounting object. */
741 		if (refs == NULL) {
742 			refs = XCALLOC(MTYPE_PRIVS,
743 				       sizeof(struct zebra_privs_refs_t));
744 			refs->tid = tid;
745 			STAILQ_INSERT_TAIL(&(privs->thread_refs), refs, entry);
746 		}
747 	}
748 
749 	return refs;
750 }
751 
_zprivs_raise(struct zebra_privs_t * privs,const char * funcname)752 struct zebra_privs_t *_zprivs_raise(struct zebra_privs_t *privs,
753 				    const char *funcname)
754 {
755 	int save_errno = errno;
756 	struct zebra_privs_refs_t *refs;
757 
758 	if (!privs)
759 		return NULL;
760 
761 	/*
762 	 * Serialize 'raise' operations; particularly important for
763 	 * OSes where privs are process-wide.
764 	 */
765 	frr_with_mutex(&(privs->mutex)) {
766 		/* Locate ref-counting object to use */
767 		refs = get_privs_refs(privs);
768 
769 		if (++(refs->refcount) == 1) {
770 			errno = 0;
771 			if (privs->change(ZPRIVS_RAISE)) {
772 				zlog_err("%s: Failed to raise privileges (%s)",
773 					 funcname, safe_strerror(errno));
774 			}
775 			errno = save_errno;
776 			refs->raised_in_funcname = funcname;
777 		}
778 	}
779 
780 	return privs;
781 }
782 
_zprivs_lower(struct zebra_privs_t ** privs)783 void _zprivs_lower(struct zebra_privs_t **privs)
784 {
785 	int save_errno = errno;
786 	struct zebra_privs_refs_t *refs;
787 
788 	if (!*privs)
789 		return;
790 
791 	/* Serialize 'lower privs' operation - particularly important
792 	 * when OS privs are process-wide.
793 	 */
794 	frr_with_mutex(&(*privs)->mutex) {
795 		refs = get_privs_refs(*privs);
796 
797 		if (--(refs->refcount) == 0) {
798 			errno = 0;
799 			if ((*privs)->change(ZPRIVS_LOWER)) {
800 				zlog_err("%s: Failed to lower privileges (%s)",
801 					 refs->raised_in_funcname,
802 					 safe_strerror(errno));
803 			}
804 			errno = save_errno;
805 			refs->raised_in_funcname = NULL;
806 		}
807 	}
808 
809 	*privs = NULL;
810 }
811 
zprivs_preinit(struct zebra_privs_t * zprivs)812 void zprivs_preinit(struct zebra_privs_t *zprivs)
813 {
814 	struct passwd *pwentry = NULL;
815 	struct group *grentry = NULL;
816 
817 	if (!zprivs) {
818 		fprintf(stderr, "zprivs_init: called with NULL arg!\n");
819 		exit(1);
820 	}
821 
822 	pthread_mutex_init(&(zprivs->mutex), NULL);
823 	zprivs->process_refs.refcount = 0;
824 	zprivs->process_refs.raised_in_funcname = NULL;
825 	STAILQ_INIT(&zprivs->thread_refs);
826 
827 	if (zprivs->vty_group) {
828 		/* in a "NULL" setup, this is allowed to fail too, but still
829 		 * try. */
830 		if ((grentry = getgrnam(zprivs->vty_group)))
831 			zprivs_state.vtygrp = grentry->gr_gid;
832 		else
833 			zprivs_state.vtygrp = (gid_t)-1;
834 	}
835 
836 	/* NULL privs */
837 	if (!(zprivs->user || zprivs->group || zprivs->cap_num_p
838 	      || zprivs->cap_num_i)) {
839 		zprivs->change = zprivs_change_null;
840 		zprivs->current_state = zprivs_state_null;
841 		return;
842 	}
843 
844 	if (zprivs->user) {
845 		if ((pwentry = getpwnam(zprivs->user)) == NULL) {
846 			/* cant use log.h here as it depends on vty */
847 			fprintf(stderr,
848 				"privs_init: could not lookup user %s\n",
849 				zprivs->user);
850 			exit(1);
851 		}
852 
853 		zprivs_state.zuid = pwentry->pw_uid;
854 		zprivs_state.zgid = pwentry->pw_gid;
855 	}
856 
857 	grentry = NULL;
858 
859 	if (zprivs->group) {
860 		if ((grentry = getgrnam(zprivs->group)) == NULL) {
861 			fprintf(stderr,
862 				"privs_init: could not lookup group %s\n",
863 				zprivs->group);
864 			exit(1);
865 		}
866 
867 		zprivs_state.zgid = grentry->gr_gid;
868 	}
869 }
870 
zprivs_init(struct zebra_privs_t * zprivs)871 void zprivs_init(struct zebra_privs_t *zprivs)
872 {
873 	gid_t groups[NGROUPS_MAX] = {};
874 	int i, ngroups = 0;
875 	int found = 0;
876 
877 	/* NULL privs */
878 	if (!(zprivs->user || zprivs->group || zprivs->cap_num_p
879 	      || zprivs->cap_num_i))
880 		return;
881 
882 	if (zprivs->user) {
883 		ngroups = array_size(groups);
884 		if (getgrouplist(zprivs->user, zprivs_state.zgid, groups,
885 				 &ngroups)
886 		    < 0) {
887 			/* cant use log.h here as it depends on vty */
888 			fprintf(stderr,
889 				"privs_init: could not getgrouplist for user %s\n",
890 				zprivs->user);
891 			exit(1);
892 		}
893 	}
894 
895 	if (zprivs->vty_group)
896 	/* Add the vty_group to the supplementary groups so it can be chowned to
897 	   */
898 	{
899 		if (zprivs_state.vtygrp == (gid_t)-1) {
900 			fprintf(stderr,
901 				"privs_init: could not lookup vty group %s\n",
902 				zprivs->vty_group);
903 			exit(1);
904 		}
905 
906 		for (i = 0; i < ngroups; i++)
907 			if (groups[i] == zprivs_state.vtygrp) {
908 				found++;
909 				break;
910 			}
911 
912 		if (!found) {
913 			fprintf(stderr,
914 				"privs_init: user(%s) is not part of vty group specified(%s)\n",
915 				zprivs->user, zprivs->vty_group);
916 			exit(1);
917 		}
918 		if (i >= ngroups && ngroups < (int)array_size(groups)) {
919 			groups[i] = zprivs_state.vtygrp;
920 		}
921 	}
922 
923 	zprivs_state.zsuid = geteuid(); /* initial uid */
924 	/* add groups only if we changed uid - otherwise skip */
925 	if ((ngroups) && (zprivs_state.zsuid != zprivs_state.zuid)) {
926 		if (setgroups(ngroups, groups)) {
927 			fprintf(stderr, "privs_init: could not setgroups, %s\n",
928 				safe_strerror(errno));
929 			exit(1);
930 		}
931 	}
932 
933 	/* change gid only if we changed uid - otherwise skip */
934 	if ((zprivs_state.zgid) && (zprivs_state.zsuid != zprivs_state.zuid)) {
935 		/* change group now, forever. uid we do later */
936 		if (setregid(zprivs_state.zgid, zprivs_state.zgid)) {
937 			fprintf(stderr, "zprivs_init: could not setregid, %s\n",
938 				safe_strerror(errno));
939 			exit(1);
940 		}
941 	}
942 
943 #ifdef HAVE_CAPABILITIES
944 	zprivs_caps_init(zprivs);
945 
946 	/*
947 	 * If we have initialized the system with no requested
948 	 * capabilities, change will not have been set
949 	 * to anything by zprivs_caps_init, As such
950 	 * we should make sure that when we attempt
951 	 * to raize privileges that we actually have
952 	 * a do nothing function to call instead of a
953 	 * crash :).
954 	 */
955 	if (!zprivs->change)
956 		zprivs->change = zprivs_change_null;
957 
958 #else  /* !HAVE_CAPABILITIES */
959 	/* we dont have caps. we'll need to maintain rid and saved uid
960 	 * and change euid back to saved uid (who we presume has all neccessary
961 	 * privileges) whenever we are asked to raise our privileges.
962 	 *
963 	 * This is not worth that much security wise, but all we can do.
964 	 */
965 	zprivs_state.zsuid = geteuid();
966 	/* only change uid if we don't have the correct one */
967 	if ((zprivs_state.zuid) && (zprivs_state.zsuid != zprivs_state.zuid)) {
968 		if (setreuid(-1, zprivs_state.zuid)) {
969 			fprintf(stderr,
970 				"privs_init (uid): could not setreuid, %s\n",
971 				safe_strerror(errno));
972 			exit(1);
973 		}
974 	}
975 
976 	zprivs->change = zprivs_change_uid;
977 	zprivs->current_state = zprivs_state_uid;
978 #endif /* HAVE_CAPABILITIES */
979 }
980 
zprivs_terminate(struct zebra_privs_t * zprivs)981 void zprivs_terminate(struct zebra_privs_t *zprivs)
982 {
983 	struct zebra_privs_refs_t *refs;
984 
985 	if (!zprivs) {
986 		fprintf(stderr, "%s: no privs struct given, terminating",
987 			__func__);
988 		exit(0);
989 	}
990 
991 #ifdef HAVE_CAPABILITIES
992 	if (zprivs->user || zprivs->group || zprivs->cap_num_p
993 	    || zprivs->cap_num_i)
994 		zprivs_caps_terminate();
995 #else  /* !HAVE_CAPABILITIES */
996 	/* only change uid if we don't have the correct one */
997 	if ((zprivs_state.zuid) && (zprivs_state.zsuid != zprivs_state.zuid)) {
998 		if (setreuid(zprivs_state.zuid, zprivs_state.zuid)) {
999 			fprintf(stderr,
1000 				"privs_terminate: could not setreuid, %s",
1001 				safe_strerror(errno));
1002 			exit(1);
1003 		}
1004 	}
1005 #endif /* HAVE_LCAPS */
1006 
1007 	while ((refs = STAILQ_FIRST(&(zprivs->thread_refs))) != NULL) {
1008 		STAILQ_REMOVE_HEAD(&(zprivs->thread_refs), entry);
1009 		XFREE(MTYPE_PRIVS, refs);
1010 	}
1011 
1012 	zprivs->change = zprivs_change_null;
1013 	zprivs->current_state = zprivs_state_null;
1014 	zprivs_null_state = ZPRIVS_LOWERED;
1015 	return;
1016 }
1017 
zprivs_get_ids(struct zprivs_ids_t * ids)1018 void zprivs_get_ids(struct zprivs_ids_t *ids)
1019 {
1020 
1021 	ids->uid_priv = getuid();
1022 	(zprivs_state.zuid) ? (ids->uid_normal = zprivs_state.zuid)
1023 			    : (ids->uid_normal = (uid_t)-1);
1024 	(zprivs_state.zgid) ? (ids->gid_normal = zprivs_state.zgid)
1025 			    : (ids->gid_normal = (uid_t)-1);
1026 	(zprivs_state.vtygrp) ? (ids->gid_vty = zprivs_state.vtygrp)
1027 			      : (ids->gid_vty = (uid_t)-1);
1028 
1029 	return;
1030 }
1031