xref: /illumos-gate/usr/src/cmd/idmap/idmapd/idmapd.c (revision 097e441f24cafd9118111f7b1b6ca3f00e5bb03f)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright 2018 Nexenta Systems, Inc.  All rights reserved.
24  */
25 
26 
27 /*
28  * main() of idmapd(1M)
29  */
30 
31 #include "idmapd.h"
32 #include <atomic.h>
33 #include <signal.h>
34 #include <rpc/pmap_clnt.h> /* for pmap_unset */
35 #include <string.h> /* strcmp */
36 #include <unistd.h> /* setsid */
37 #include <sys/types.h>
38 #include <memory.h>
39 #include <stropts.h>
40 #include <netconfig.h>
41 #include <sys/resource.h> /* rlimit */
42 #include <rpcsvc/daemon_utils.h> /* DAEMON_UID and DAEMON_GID */
43 #include <priv_utils.h> /* privileges */
44 #include <locale.h>
45 #include <sys/systeminfo.h>
46 #include <errno.h>
47 #include <sys/wait.h>
48 #include <sys/time.h>
49 #include <zone.h>
50 #include <door.h>
51 #include <port.h>
52 #include <tsol/label.h>
53 #include <sys/resource.h>
54 #include <sys/sid.h>
55 #include <sys/idmap.h>
56 #include <pthread.h>
57 #include <stdarg.h>
58 #include <assert.h>
59 #include <note.h>
60 
61 #define	CBUFSIZ 26	/* ctime(3c) */
62 
63 static void	term_handler(int);
64 static void	init_idmapd();
65 static void	fini_idmapd();
66 
67 /* The DC Locator lives inside idmap (for now). */
68 extern void	init_dc_locator(void);
69 extern void	fini_dc_locator(void);
70 
71 idmapd_state_t	_idmapdstate;
72 mutex_t _svcstate_lock = ERRORCHECKMUTEX;
73 
74 SVCXPRT *xprt = NULL;
75 
76 static int dfd = -1;		/* our door server fildes, for unregistration */
77 static boolean_t degraded = B_FALSE;
78 
79 
80 static uint32_t		num_threads = 0;
81 static pthread_key_t	create_threads_key;
82 static uint32_t		max_threads = 40;
83 
84 /*
85  * Server door thread start routine.
86  *
87  * Set a TSD value to the door thread. This enables the destructor to
88  * be called when this thread exits. Note that we need a non-NULL
89  * value for this or the TSD destructor is not called.
90  */
91 /*ARGSUSED*/
92 static void *
93 idmapd_door_thread_start(void *arg)
94 {
95 	static void *value = "NON-NULL TSD";
96 
97 	/*
98 	 * Disable cancellation to avoid memory leaks from not running
99 	 * the thread cleanup code.
100 	 */
101 	(void) pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
102 	(void) pthread_setspecific(create_threads_key, value);
103 	(void) door_return(NULL, 0, NULL, 0);
104 
105 	/* make lint happy */
106 	return (NULL);
107 }
108 
109 /*
110  * Server door threads creation
111  */
112 /*ARGSUSED*/
113 static void
114 idmapd_door_thread_create(door_info_t *dip)
115 {
116 	int		num;
117 	pthread_t	thread_id;
118 
119 	if ((num = atomic_inc_32_nv(&num_threads)) > max_threads) {
120 		atomic_dec_32(&num_threads);
121 		idmapdlog(LOG_DEBUG,
122 		    "thread creation refused - %d threads currently active",
123 		    num - 1);
124 		return;
125 	}
126 	(void) pthread_create(&thread_id, NULL, idmapd_door_thread_start, NULL);
127 	idmapdlog(LOG_DEBUG,
128 	    "created thread ID %d - %d threads currently active",
129 	    thread_id, num);
130 }
131 
132 /*
133  * Server door thread cleanup
134  */
135 /*ARGSUSED*/
136 static void
137 idmapd_door_thread_cleanup(void *arg)
138 {
139 	int num;
140 
141 	/* set TSD to NULL so we don't loop infinitely */
142 	(void) pthread_setspecific(create_threads_key, NULL);
143 	num = atomic_dec_32_nv(&num_threads);
144 	idmapdlog(LOG_DEBUG,
145 	    "exiting thread ID %d - %d threads currently active",
146 	    pthread_self(), num);
147 }
148 
149 /*
150  * This is needed for mech_krb5 -- we run as daemon, yes, but we want
151  * mech_krb5 to think we're root so it can get host/nodename.fqdn
152  * tickets for us so we can authenticate to AD as the machine account
153  * that we are.  For more details look at the entry point in mech_krb5
154  * corresponding to gss_init_sec_context().
155  *
156  * As a side effect of faking our effective UID to mech_krb5 we will use
157  * root's default ccache (/tmp/krb5cc_0).  But if that's created by
158  * another process then we won't have access to it: we run as daemon and
159  * keep PRIV_FILE_DAC_READ, which is insufficient to share the ccache
160  * with others.  We putenv("KRB5CCNAME=/var/run/idmap/ccache") in main()
161  * to avoid this issue; see main().
162  *
163  * Someday we'll have gss/mech_krb5 extensions for acquiring initiator
164  * creds with keytabs/raw keys, and someday we'll have extensions to
165  * libsasl to specify creds/name to use on the initiator side, and
166  * someday we'll have extensions to libldap to pass those through to
167  * libsasl.  Until then this interposer will have to do.
168  *
169  * Also, we have to tell lint to shut up: it thinks app_krb5_user_uid()
170  * is defined but not used.
171  */
172 /*LINTLIBRARY*/
173 uid_t
174 app_krb5_user_uid(void)
175 {
176 	return (0);
177 }
178 
179 /*ARGSUSED*/
180 static void
181 term_handler(int sig)
182 {
183 	idmapdlog(LOG_INFO, "Terminating.");
184 	fini_dc_locator();
185 	fini_idmapd();
186 	_exit(0);
187 }
188 
189 /*ARGSUSED*/
190 static void
191 usr1_handler(int sig)
192 {
193 	NOTE(ARGUNUSED(sig))
194 	print_idmapdstate();
195 }
196 
197 static int pipe_fd = -1;
198 
199 static void
200 daemonize_ready(void)
201 {
202 	char data = '\0';
203 	/*
204 	 * wake the parent
205 	 */
206 	(void) write(pipe_fd, &data, 1);
207 	(void) close(pipe_fd);
208 }
209 
210 static int
211 daemonize_start(void)
212 {
213 	char	data;
214 	int	status;
215 	int	devnull;
216 	int	filedes[2];
217 	pid_t	pid;
218 
219 	(void) sigset(SIGPIPE, SIG_IGN);
220 	devnull = open("/dev/null", O_RDONLY);
221 	if (devnull < 0)
222 		return (-1);
223 	(void) dup2(devnull, 0);
224 	(void) dup2(2, 1);	/* stderr only */
225 	if (pipe(filedes) < 0)
226 		return (-1);
227 	if ((pid = fork1()) < 0)
228 		return (-1);
229 	if (pid != 0) {
230 		/*
231 		 * parent
232 		 */
233 		(void) close(filedes[1]);
234 		if (read(filedes[0], &data, 1) == 1) {
235 			/* presume success */
236 			_exit(0);
237 		}
238 		status = -1;
239 		(void) wait4(pid, &status, 0, NULL);
240 		if (WIFEXITED(status))
241 			_exit(WEXITSTATUS(status));
242 		else
243 			_exit(-1);
244 	}
245 
246 	/*
247 	 * child
248 	 */
249 	pipe_fd = filedes[1];
250 	(void) close(filedes[0]);
251 	(void) setsid();
252 	(void) umask(0077);
253 	openlog("idmap", LOG_PID, LOG_DAEMON);
254 
255 	return (0);
256 }
257 
258 
259 int
260 main(int argc, char **argv)
261 {
262 	int c;
263 	struct rlimit rl;
264 
265 	if (rwlock_init(&_idmapdstate.rwlk_cfg, USYNC_THREAD, NULL) != 0)
266 		return (-1);
267 	if (mutex_init(&_idmapdstate.addisc_lk, USYNC_THREAD, NULL) != 0)
268 		return (-1);
269 	if (cond_init(&_idmapdstate.addisc_cv, USYNC_THREAD, NULL) != 0)
270 		return (-1);
271 
272 	_idmapdstate.daemon_mode = TRUE;
273 	while ((c = getopt(argc, argv, "d")) != -1) {
274 		switch (c) {
275 			case 'd':
276 				_idmapdstate.daemon_mode = FALSE;
277 				break;
278 			default:
279 				(void) fprintf(stderr,
280 				    "Usage: /usr/lib/idmapd [-d]\n");
281 				return (SMF_EXIT_ERR_CONFIG);
282 		}
283 	}
284 
285 	/* set locale and domain for internationalization */
286 	(void) setlocale(LC_ALL, "");
287 	(void) textdomain(TEXT_DOMAIN);
288 
289 	idmap_set_logger(idmapdlog);
290 	adutils_set_logger(idmapdlog);
291 
292 	if (is_system_labeled() && getzoneid() != GLOBAL_ZONEID) {
293 		idmapdlog(LOG_ERR,
294 		    "with Trusted Extensions idmapd runs only in the "
295 		    "global zone");
296 		exit(1);
297 	}
298 
299 	/*
300 	 * Raise the fd limit to max
301 	 */
302 	if (getrlimit(RLIMIT_NOFILE, &rl) != 0) {
303 		idmapdlog(LOG_ERR, "getrlimit failed");
304 	} else if (rl.rlim_cur < rl.rlim_max) {
305 		rl.rlim_cur = rl.rlim_max;
306 		if (setrlimit(RLIMIT_NOFILE, &rl) != 0)
307 			idmapdlog(LOG_ERR,
308 			    "Unable to raise RLIMIT_NOFILE to %d",
309 			    rl.rlim_cur);
310 	}
311 
312 	if (_idmapdstate.daemon_mode == TRUE) {
313 		if (daemonize_start() < 0) {
314 			idmapdlog(LOG_ERR, "unable to daemonize");
315 			exit(-1);
316 		}
317 	} else
318 		(void) umask(0077);
319 
320 	idmap_init_tsd_key();
321 
322 	init_idmapd();
323 	init_dc_locator();
324 
325 	/* signal handlers that should run only after we're initialized */
326 	(void) sigset(SIGTERM, term_handler);
327 	(void) sigset(SIGUSR1, usr1_handler);
328 	(void) sigset(SIGHUP, idmap_cfg_hup_handler);
329 
330 	if (__init_daemon_priv(PU_RESETGROUPS|PU_CLEARLIMITSET,
331 	    DAEMON_UID, DAEMON_GID,
332 	    PRIV_PROC_AUDIT, PRIV_FILE_DAC_READ,
333 	    (char *)NULL) == -1) {
334 		idmapdlog(LOG_ERR, "unable to drop privileges");
335 		exit(1);
336 	}
337 
338 	__fini_daemon_priv(PRIV_PROC_FORK, PRIV_PROC_EXEC, PRIV_PROC_SESSION,
339 	    PRIV_FILE_LINK_ANY, PRIV_PROC_INFO, (char *)NULL);
340 
341 	if (_idmapdstate.daemon_mode == TRUE)
342 		daemonize_ready();
343 
344 	/* With doors RPC this just wastes this thread, oh well */
345 	svc_run();
346 	return (0);
347 }
348 
349 static void
350 init_idmapd()
351 {
352 	int	error;
353 	int	connmaxrec = IDMAP_MAX_DOOR_RPC;
354 
355 
356 	/* create directories as root and chown to daemon uid */
357 	if (create_directory(IDMAP_DBDIR, DAEMON_UID, DAEMON_GID) < 0)
358 		exit(1);
359 	if (create_directory(IDMAP_CACHEDIR, DAEMON_UID, DAEMON_GID) < 0)
360 		exit(1);
361 
362 	/*
363 	 * Set KRB5CCNAME in the environment.  See app_krb5_user_uid()
364 	 * for more details.  We blow away the existing one, if there is
365 	 * one.
366 	 */
367 	(void) unlink(IDMAP_CACHEDIR "/ccache");
368 	(void) putenv("KRB5CCNAME=" IDMAP_CACHEDIR "/ccache");
369 	(void) putenv("MS_INTEROP=1");
370 
371 	if (sysinfo(SI_HOSTNAME, _idmapdstate.hostname,
372 	    sizeof (_idmapdstate.hostname)) == -1) {
373 		error = errno;
374 		idmapdlog(LOG_ERR, "unable to determine hostname, error: %d",
375 		    error);
376 		exit(1);
377 	}
378 
379 	if ((error = init_mapping_system()) < 0) {
380 		idmapdlog(LOG_ERR, "unable to initialize mapping system");
381 		exit(error < -2 ? SMF_EXIT_ERR_CONFIG : 1);
382 	}
383 
384 	/*
385 	 * This means max_threads can't be updated without restarting idmap.
386 	 */
387 	RDLOCK_CONFIG();
388 	max_threads = _idmapdstate.cfg->pgcfg.max_threads;
389 	UNLOCK_CONFIG();
390 
391 	(void) door_server_create(idmapd_door_thread_create);
392 	if ((error = pthread_key_create(&create_threads_key,
393 	    idmapd_door_thread_cleanup)) != 0) {
394 		idmapdlog(LOG_ERR, "unable to create threads key (%s)",
395 		    strerror(error));
396 		goto errout;
397 	}
398 
399 	xprt = svc_door_create(idmap_prog_1, IDMAP_PROG, IDMAP_V1, connmaxrec);
400 	if (xprt == NULL) {
401 		idmapdlog(LOG_ERR, "unable to create door RPC service");
402 		goto errout;
403 	}
404 
405 	if (!svc_control(xprt, SVCSET_CONNMAXREC, &connmaxrec)) {
406 		idmapdlog(LOG_ERR, "unable to limit RPC request size");
407 		goto errout;
408 	}
409 
410 	dfd = xprt->xp_fd;
411 
412 	if (dfd == -1) {
413 		idmapdlog(LOG_ERR, "unable to register door");
414 		goto errout;
415 	}
416 	if ((error = __idmap_reg(dfd)) != 0) {
417 		idmapdlog(LOG_ERR, "unable to register door (%s)",
418 		    strerror(errno));
419 		goto errout;
420 	}
421 
422 	if ((error = allocids(_idmapdstate.new_eph_db,
423 	    8192, &_idmapdstate.next_uid,
424 	    8192, &_idmapdstate.next_gid)) != 0) {
425 		idmapdlog(LOG_ERR, "unable to allocate ephemeral IDs (%s)",
426 		    strerror(errno));
427 		_idmapdstate.next_uid = IDMAP_SENTINEL_PID;
428 		_idmapdstate.limit_uid = IDMAP_SENTINEL_PID;
429 		_idmapdstate.next_gid = IDMAP_SENTINEL_PID;
430 		_idmapdstate.limit_gid = IDMAP_SENTINEL_PID;
431 	} else {
432 		_idmapdstate.limit_uid = _idmapdstate.next_uid + 8192;
433 		_idmapdstate.limit_gid = _idmapdstate.next_gid + 8192;
434 	}
435 
436 	if (DBG(CONFIG, 1))
437 		print_idmapdstate();
438 
439 	return;
440 
441 errout:
442 	fini_idmapd();
443 	exit(1);
444 }
445 
446 static void
447 fini_idmapd()
448 {
449 	(void) __idmap_unreg(dfd);
450 	fini_mapping_system();
451 	if (xprt != NULL)
452 		svc_destroy(xprt);
453 }
454 
455 static
456 const char *
457 get_fmri(void)
458 {
459 	static char *fmri = NULL;
460 	static char buf[60];
461 	char *s;
462 
463 	membar_consumer();
464 	s = fmri;
465 	if (s != NULL && *s == '\0')
466 		return (NULL);
467 	else if (s != NULL)
468 		return (s);
469 
470 	if ((s = getenv("SMF_FMRI")) == NULL || strlen(s) >= sizeof (buf))
471 		buf[0] = '\0';
472 	else
473 		(void) strlcpy(buf, s, sizeof (buf));
474 
475 	membar_producer();
476 	fmri = buf;
477 
478 	return (get_fmri());
479 }
480 
481 /*
482  * Wrappers for smf_degrade/restore_instance()
483  *
484  * smf_restore_instance() is too heavy duty to be calling every time we
485  * have a successful AD name<->SID lookup.
486  */
487 void
488 degrade_svc(int poke_discovery, const char *reason)
489 {
490 	const char *fmri;
491 
492 	membar_consumer();
493 	if (degraded)
494 		return;
495 
496 	idmapdlog(LOG_ERR, "Degraded operation (%s).", reason);
497 
498 	membar_producer();
499 	degraded = B_TRUE;
500 
501 	if ((fmri = get_fmri()) != NULL)
502 		(void) smf_degrade_instance(fmri, 0);
503 
504 	/*
505 	 * If the config update thread is in a state where auto-discovery could
506 	 * be re-tried, then this will make it try it -- a sort of auto-refresh.
507 	 */
508 	if (poke_discovery)
509 		idmap_cfg_poke_updates();
510 }
511 
512 void
513 restore_svc(void)
514 {
515 	const char *fmri;
516 
517 	membar_consumer();
518 	if (!degraded)
519 		return;
520 
521 	if ((fmri = get_fmri()) == NULL)
522 		(void) smf_restore_instance(fmri);
523 
524 	membar_producer();
525 	degraded = B_FALSE;
526 
527 	idmapdlog(LOG_NOTICE, "Normal operation restored");
528 }
529 
530 
531 /* printflike */
532 void
533 idmapdlog(int pri, const char *format, ...)
534 {
535 	static time_t prev_ts;
536 	va_list args;
537 	char cbuf[CBUFSIZ];
538 	time_t ts;
539 
540 	ts = time(NULL);
541 	if (prev_ts != ts) {
542 		prev_ts = ts;
543 		/* NB: cbuf has \n */
544 		(void) fprintf(stderr, "@ %s",
545 		    ctime_r(&ts, cbuf, sizeof (cbuf)));
546 	}
547 
548 	va_start(args, format);
549 	(void) vfprintf(stderr, format, args);
550 	(void) fprintf(stderr, "\n");
551 	va_end(args);
552 
553 	/*
554 	 * We don't want to fill up the logs with useless messages when
555 	 * we're degraded, but we still want to log.
556 	 */
557 	if (degraded)
558 		pri = LOG_DEBUG;
559 
560 	va_start(args, format);
561 	vsyslog(pri, format, args);
562 	va_end(args);
563 }
564 
565 static void
566 trace_str(nvlist_t *entry, char *n1, char *n2, char *str)
567 {
568 	char name[IDMAP_TRACE_NAME_MAX+1];	/* Max used is only about 11 */
569 
570 	(void) strlcpy(name, n1, sizeof (name));
571 	if (n2 != NULL)
572 		(void) strlcat(name, n2, sizeof (name));
573 
574 	(void) nvlist_add_string(entry, name, str);
575 }
576 
577 static void
578 trace_int(nvlist_t *entry, char *n1, char *n2, int64_t i)
579 {
580 	char name[IDMAP_TRACE_NAME_MAX+1];	/* Max used is only about 11 */
581 
582 	(void) strlcpy(name, n1, sizeof (name));
583 	if (n2 != NULL)
584 		(void) strlcat(name, n2, sizeof (name));
585 
586 	(void) nvlist_add_int64(entry, name, i);
587 }
588 
589 static void
590 trace_sid(nvlist_t *entry, char *n1, char *n2, idmap_sid *sid)
591 {
592 	char *str;
593 
594 	(void) asprintf(&str, "%s-%u", sid->prefix, sid->rid);
595 	if (str == NULL)
596 		return;
597 
598 	trace_str(entry, n1, n2, str);
599 	free(str);
600 }
601 
602 static void
603 trace_id(nvlist_t *entry, char *fromto, idmap_id *id, char *name, char *domain)
604 {
605 	trace_int(entry, fromto, IDMAP_TRACE_TYPE, (int64_t)id->idtype);
606 	if (IS_ID_SID(*id)) {
607 		if (name != NULL) {
608 			char *str;
609 
610 			(void) asprintf(&str, "%s%s%s", name,
611 			    domain == NULL ? "" : "@",
612 			    domain == NULL ? "" : domain);
613 			if (str != NULL) {
614 				trace_str(entry, fromto, IDMAP_TRACE_NAME, str);
615 				free(str);
616 			}
617 		}
618 		if (id->idmap_id_u.sid.prefix != NULL) {
619 			trace_sid(entry, fromto, IDMAP_TRACE_SID,
620 			    &id->idmap_id_u.sid);
621 		}
622 	} else if (IS_ID_POSIX(*id)) {
623 		if (name != NULL)
624 			trace_str(entry, fromto, IDMAP_TRACE_NAME, name);
625 		if (id->idmap_id_u.uid != IDMAP_SENTINEL_PID) {
626 			trace_int(entry, fromto, IDMAP_TRACE_UNIXID,
627 			    (int64_t)id->idmap_id_u.uid);
628 		}
629 	}
630 }
631 
632 /*
633  * Record a trace event.  TRACE() has already decided whether or not
634  * tracing is required; what we do here is collect the data and send it
635  * to its destination - to the trace log in the response, if
636  * IDMAP_REQ_FLG_TRACE is set, and to the SMF service log, if debug/mapping
637  * is greater than zero.
638  */
639 int
640 trace(idmap_mapping *req, idmap_id_res *res, char *fmt, ...)
641 {
642 	va_list va;
643 	char *buf;
644 	int err;
645 	nvlist_t *entry;
646 
647 	assert(req != NULL);
648 	assert(res != NULL);
649 
650 	err = nvlist_alloc(&entry, NV_UNIQUE_NAME, 0);
651 	if (err != 0) {
652 		(void) fprintf(stderr, "trace nvlist_alloc(entry):  %s\n",
653 		    strerror(err));
654 		return (0);
655 	}
656 
657 	trace_id(entry, "from", &req->id1, req->id1name, req->id1domain);
658 	trace_id(entry, "to", &res->id, req->id2name, req->id2domain);
659 
660 	if (IDMAP_ERROR(res->retcode)) {
661 		trace_int(entry, IDMAP_TRACE_ERROR, NULL,
662 		    (int64_t)res->retcode);
663 	}
664 
665 	va_start(va, fmt);
666 	(void) vasprintf(&buf, fmt, va);
667 	va_end(va);
668 	if (buf != NULL) {
669 		trace_str(entry, IDMAP_TRACE_MESSAGE, NULL, buf);
670 		free(buf);
671 	}
672 
673 	if (DBG(MAPPING, 1))
674 		idmap_trace_print_1(stderr, "", entry);
675 
676 	if (req->flag & IDMAP_REQ_FLG_TRACE) {
677 		/* Lazily allocate the trace list */
678 		if (res->info.trace == NULL) {
679 			err = nvlist_alloc(&res->info.trace, 0, 0);
680 			if (err != 0) {
681 				res->info.trace = NULL; /* just in case */
682 				(void) fprintf(stderr,
683 				    "trace nvlist_alloc(trace):  %s\n",
684 				    strerror(err));
685 				nvlist_free(entry);
686 				return (0);
687 			}
688 		}
689 		(void) nvlist_add_nvlist(res->info.trace, "", entry);
690 		/* Note that entry is copied, so we must still free our copy */
691 	}
692 
693 	nvlist_free(entry);
694 
695 	return (0);
696 }
697