xref: /illumos-gate/usr/src/cmd/idmap/idmapd/dbutils.c (revision 24987e92ed84693f7d1351de150743664658894f)
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 2016 Nexenta Systems, Inc.  All rights reserved.
24  * Copyright 2022 RackTop Systems, Inc.
25  * Copyright 2025 Bill Sommerfeld
26  */
27 
28 /*
29  * Database related utility routines
30  */
31 
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <errno.h>
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <rpc/rpc.h>
39 #include <sys/sid.h>
40 #include <time.h>
41 #include <pwd.h>
42 #include <grp.h>
43 #include <pthread.h>
44 #include <assert.h>
45 #include <sys/u8_textprep.h>
46 #include <alloca.h>
47 #include <libuutil.h>
48 #include <note.h>
49 
50 #include "idmapd.h"
51 #include "adutils.h"
52 #include "string.h"
53 #include "idmap_priv.h"
54 #include "schema.h"
55 #include "nldaputils.h"
56 #include "idmap_lsa.h"
57 
58 
59 static idmap_retcode sql_compile_n_step_once(sqlite *, char *,
60 		sqlite_vm **, int *, int, const char ***);
61 static idmap_retcode lookup_localsid2pid(idmap_mapping *, idmap_id_res *);
62 static idmap_retcode lookup_cache_name2sid(sqlite *, const char *,
63 	    const char *, char **, char **, idmap_rid_t *, idmap_id_type *);
64 
65 #define	EMPTY_NAME(name)	(*name == 0 || strcmp(name, "\"\"") == 0)
66 
67 #define	DO_NOT_ALLOC_NEW_ID_MAPPING(req)\
68 		(req->flag & IDMAP_REQ_FLG_NO_NEW_ID_ALLOC)
69 
70 #define	AVOID_NAMESERVICE(req)\
71 		(req->flag & IDMAP_REQ_FLG_NO_NAMESERVICE)
72 
73 #define	ALLOW_WK_OR_LOCAL_SIDS_ONLY(req)\
74 		(req->flag & IDMAP_REQ_FLG_WK_OR_LOCAL_SIDS_ONLY)
75 
76 typedef enum init_db_option {
77 	FAIL_IF_CORRUPT = 0,
78 	REMOVE_IF_CORRUPT = 1
79 } init_db_option_t;
80 
81 /*
82  * Thread specific data to hold the database handles so that the
83  * databases are not opened and closed for every request. It also
84  * contains the sqlite busy handler structure.
85  */
86 
87 struct idmap_busy {
88 	const char *name;
89 	const int *delays;
90 	int delay_size;
91 	int total;
92 	int sec;
93 };
94 
95 
96 typedef struct idmap_tsd {
97 	sqlite *db_db;
98 	sqlite *cache_db;
99 	struct idmap_busy cache_busy;
100 	struct idmap_busy db_busy;
101 } idmap_tsd_t;
102 
103 /*
104  * Flags to indicate how local the directory we're consulting is.
105  * If neither is set, it means the directory belongs to a remote forest.
106  */
107 #define	DOMAIN_IS_LOCAL	0x01
108 #define	FOREST_IS_LOCAL	0x02
109 
110 static const int cache_delay_table[] =
111 		{ 1, 2, 5, 10, 15, 20, 25, 30,  35,  40,
112 		50,  50, 60, 70, 80, 90, 100};
113 
114 static const int db_delay_table[] =
115 		{ 5, 10, 15, 20, 30,  40,  55,  70, 100};
116 
117 
118 static pthread_key_t	idmap_tsd_key;
119 
120 void
idmap_tsd_destroy(void * key)121 idmap_tsd_destroy(void *key)
122 {
123 
124 	idmap_tsd_t	*tsd = (idmap_tsd_t *)key;
125 	if (tsd) {
126 		if (tsd->db_db)
127 			(void) sqlite_close(tsd->db_db);
128 		if (tsd->cache_db)
129 			(void) sqlite_close(tsd->cache_db);
130 		free(tsd);
131 	}
132 }
133 
134 void
idmap_init_tsd_key(void)135 idmap_init_tsd_key(void)
136 {
137 	int rc;
138 
139 	rc = pthread_key_create(&idmap_tsd_key, idmap_tsd_destroy);
140 	assert(rc == 0);
141 }
142 
143 
144 
145 idmap_tsd_t *
idmap_get_tsd(void)146 idmap_get_tsd(void)
147 {
148 	idmap_tsd_t	*tsd;
149 
150 	if ((tsd = pthread_getspecific(idmap_tsd_key)) == NULL) {
151 		/* No thread specific data so create it */
152 		if ((tsd = malloc(sizeof (*tsd))) != NULL) {
153 			/* Initialize thread specific data */
154 			(void) memset(tsd, 0, sizeof (*tsd));
155 			/* save the trhread specific data */
156 			if (pthread_setspecific(idmap_tsd_key, tsd) != 0) {
157 				/* Can't store key */
158 				free(tsd);
159 				tsd = NULL;
160 			}
161 		} else {
162 			tsd = NULL;
163 		}
164 	}
165 
166 	return (tsd);
167 }
168 
169 /*
170  * A simple wrapper around u8_textprep_str() that returns the Unicode
171  * lower-case version of some string.  The result must be freed.
172  */
173 char *
tolower_u8(const char * s)174 tolower_u8(const char *s)
175 {
176 	char *res = NULL;
177 	char *outs;
178 	size_t inlen, outlen, inbytesleft, outbytesleft;
179 	int rc, err;
180 
181 	/*
182 	 * u8_textprep_str() does not allocate memory.  The input and
183 	 * output buffers may differ in size (though that would be more
184 	 * likely when normalization is done).  We have to loop over it...
185 	 *
186 	 * To improve the chances that we can avoid looping we add 10
187 	 * bytes of output buffer room the first go around.
188 	 */
189 	inlen = inbytesleft = strlen(s);
190 	outlen = outbytesleft = inlen + 10;
191 	if ((res = malloc(outlen)) == NULL)
192 		return (NULL);
193 	outs = res;
194 
195 	while ((rc = u8_textprep_str((char *)s, &inbytesleft, outs,
196 	    &outbytesleft, U8_TEXTPREP_TOLOWER, U8_UNICODE_LATEST, &err)) < 0 &&
197 	    err == E2BIG) {
198 		if ((res = realloc(res, outlen + inbytesleft)) == NULL)
199 			return (NULL);
200 		/* adjust input/output buffer pointers */
201 		s += (inlen - inbytesleft);
202 		outs = res + outlen - outbytesleft;
203 		/* adjust outbytesleft and outlen */
204 		outlen += inbytesleft;
205 		outbytesleft += inbytesleft;
206 	}
207 
208 	if (rc < 0) {
209 		free(res);
210 		res = NULL;
211 		return (NULL);
212 	}
213 
214 	res[outlen - outbytesleft] = '\0';
215 
216 	return (res);
217 }
218 
219 static int sql_exec_tran_no_cb(sqlite *db, char *sql, const char *dbname,
220 	const char *while_doing);
221 
222 
223 /*
224  * Initialize 'dbname' using 'sql'
225  */
226 static
227 int
init_db_instance(const char * dbname,int version,const char * detect_version_sql,char * const * sql,init_db_option_t opt,int * created,int * upgraded)228 init_db_instance(const char *dbname, int version,
229     const char *detect_version_sql, char * const *sql,
230     init_db_option_t opt, int *created, int *upgraded)
231 {
232 	int rc, curr_version;
233 	int tries = 1;
234 	int prio = LOG_NOTICE;
235 	sqlite *db = NULL;
236 	char *errmsg = NULL;
237 
238 	*created = 0;
239 	*upgraded = 0;
240 
241 	if (opt == REMOVE_IF_CORRUPT)
242 		tries = 3;
243 
244 rinse_repeat:
245 	if (tries == 0) {
246 		idmapdlog(LOG_ERR, "Failed to initialize db %s", dbname);
247 		return (-1);
248 	}
249 	if (tries-- == 1)
250 		/* Last try, log errors */
251 		prio = LOG_ERR;
252 
253 	db = sqlite_open(dbname, 0600, &errmsg);
254 	if (db == NULL) {
255 		idmapdlog(prio, "Error creating database %s (%s)",
256 		    dbname, CHECK_NULL(errmsg));
257 		sqlite_freemem(errmsg);
258 		if (opt == REMOVE_IF_CORRUPT)
259 			(void) unlink(dbname);
260 		goto rinse_repeat;
261 	}
262 
263 	sqlite_busy_timeout(db, 3000);
264 
265 	/* Detect current version of schema in the db, if any */
266 	curr_version = 0;
267 	if (detect_version_sql != NULL) {
268 		char *end, **results;
269 		int nrow;
270 
271 #ifdef	IDMAPD_DEBUG
272 		(void) fprintf(stderr, "Schema version detection SQL: %s\n",
273 		    detect_version_sql);
274 #endif	/* IDMAPD_DEBUG */
275 		rc = sqlite_get_table(db, detect_version_sql, &results,
276 		    &nrow, NULL, &errmsg);
277 		if (rc != SQLITE_OK) {
278 			idmapdlog(prio,
279 			    "Error detecting schema version of db %s (%s)",
280 			    dbname, errmsg);
281 			sqlite_freemem(errmsg);
282 			sqlite_free_table(results);
283 			sqlite_close(db);
284 			return (-1);
285 		}
286 		if (nrow != 1) {
287 			idmapdlog(prio,
288 			    "Error detecting schema version of db %s", dbname);
289 			sqlite_close(db);
290 			sqlite_free_table(results);
291 			return (-1);
292 		}
293 		curr_version = strtol(results[1], &end, 10);
294 		sqlite_free_table(results);
295 	}
296 
297 	if (curr_version < 0) {
298 		if (opt == REMOVE_IF_CORRUPT)
299 			(void) unlink(dbname);
300 		goto rinse_repeat;
301 	}
302 
303 	if (curr_version == version)
304 		goto done;
305 
306 	/* Install or upgrade schema */
307 #ifdef	IDMAPD_DEBUG
308 	(void) fprintf(stderr, "Schema init/upgrade SQL: %s\n",
309 	    sql[curr_version]);
310 #endif	/* IDMAPD_DEBUG */
311 	rc = sql_exec_tran_no_cb(db, sql[curr_version], dbname,
312 	    (curr_version == 0) ? "installing schema" : "upgrading schema");
313 	if (rc != 0) {
314 		idmapdlog(prio, "Error %s schema for db %s", dbname,
315 		    (curr_version == 0) ? "installing schema" :
316 		    "upgrading schema");
317 		if (opt == REMOVE_IF_CORRUPT)
318 			(void) unlink(dbname);
319 		goto rinse_repeat;
320 	}
321 
322 	*upgraded = (curr_version > 0);
323 	*created = (curr_version == 0);
324 
325 done:
326 	(void) sqlite_close(db);
327 	return (0);
328 }
329 
330 
331 /*
332  * This is the SQLite database busy handler that retries the SQL
333  * operation until it is successful.
334  */
335 int
idmap_sqlite_busy_handler(void * arg,const char * table_name,int count)336 idmap_sqlite_busy_handler(void *arg, const char *table_name, int count)
337 {
338 	struct idmap_busy	*busy = arg;
339 	int			delay;
340 	struct timespec		rqtp;
341 
342 	if (count == 1)  {
343 		busy->total = 0;
344 		busy->sec = 2;
345 	}
346 	if (busy->total > 1000 * busy->sec) {
347 		idmapdlog(LOG_DEBUG,
348 		    "Thread %d waited %d sec for the %s database",
349 		    pthread_self(), busy->sec, busy->name);
350 		busy->sec++;
351 	}
352 
353 	if (count <= busy->delay_size) {
354 		delay = busy->delays[count-1];
355 	} else {
356 		delay = busy->delays[busy->delay_size - 1];
357 	}
358 	busy->total += delay;
359 	rqtp.tv_sec = 0;
360 	rqtp.tv_nsec = MSEC2NSEC(delay);
361 	(void) nanosleep(&rqtp, NULL);
362 	return (1);
363 }
364 
365 
366 /*
367  * Get the database handle
368  */
369 idmap_retcode
get_db_handle(sqlite ** db)370 get_db_handle(sqlite **db)
371 {
372 	char		*errmsg;
373 	idmap_tsd_t	*tsd;
374 
375 	/*
376 	 * Retrieve the db handle from thread-specific storage
377 	 * If none exists, open and store in thread-specific storage.
378 	 */
379 	if ((tsd = idmap_get_tsd()) == NULL) {
380 		idmapdlog(LOG_ERR,
381 		    "Error getting thread specific data for %s", IDMAP_DBNAME);
382 		return (IDMAP_ERR_MEMORY);
383 	}
384 
385 	if (tsd->db_db == NULL) {
386 		tsd->db_db = sqlite_open(IDMAP_DBNAME, 0, &errmsg);
387 		if (tsd->db_db == NULL) {
388 			idmapdlog(LOG_ERR, "Error opening database %s (%s)",
389 			    IDMAP_DBNAME, CHECK_NULL(errmsg));
390 			sqlite_freemem(errmsg);
391 			return (IDMAP_ERR_DB);
392 		}
393 
394 		tsd->db_busy.name = IDMAP_DBNAME;
395 		tsd->db_busy.delays = db_delay_table;
396 		tsd->db_busy.delay_size = sizeof (db_delay_table) /
397 		    sizeof (int);
398 		sqlite_busy_handler(tsd->db_db, idmap_sqlite_busy_handler,
399 		    &tsd->db_busy);
400 	}
401 	*db = tsd->db_db;
402 	return (IDMAP_SUCCESS);
403 }
404 
405 /*
406  * Force next get_db_handle to reopen.
407  * Called after DB errors.
408  */
409 void
kill_db_handle(sqlite * db)410 kill_db_handle(sqlite *db)
411 {
412 	idmap_tsd_t	*tsd;
413 	sqlite		*t;
414 
415 	if (db == NULL)
416 		return;
417 
418 	if ((tsd = idmap_get_tsd()) == NULL)
419 		return;
420 
421 	if ((t = tsd->db_db) == NULL)
422 		return;
423 	assert(t == db);
424 	tsd->db_db = NULL;
425 	(void) sqlite_close(t);
426 }
427 
428 /*
429  * Get the cache handle
430  */
431 idmap_retcode
get_cache_handle(sqlite ** cache)432 get_cache_handle(sqlite **cache)
433 {
434 	char		*errmsg;
435 	idmap_tsd_t	*tsd;
436 
437 	/*
438 	 * Retrieve the db handle from thread-specific storage
439 	 * If none exists, open and store in thread-specific storage.
440 	 */
441 	if ((tsd = idmap_get_tsd()) == NULL) {
442 		idmapdlog(LOG_ERR, "Error getting thread specific data for %s",
443 		    IDMAP_DBNAME);
444 		return (IDMAP_ERR_MEMORY);
445 	}
446 
447 	if (tsd->cache_db == NULL) {
448 		tsd->cache_db = sqlite_open(IDMAP_CACHENAME, 0, &errmsg);
449 		if (tsd->cache_db == NULL) {
450 			idmapdlog(LOG_ERR, "Error opening database %s (%s)",
451 			    IDMAP_CACHENAME, CHECK_NULL(errmsg));
452 			sqlite_freemem(errmsg);
453 			return (IDMAP_ERR_DB);
454 		}
455 
456 		tsd->cache_busy.name = IDMAP_CACHENAME;
457 		tsd->cache_busy.delays = cache_delay_table;
458 		tsd->cache_busy.delay_size = sizeof (cache_delay_table) /
459 		    sizeof (int);
460 		sqlite_busy_handler(tsd->cache_db, idmap_sqlite_busy_handler,
461 		    &tsd->cache_busy);
462 	}
463 	*cache = tsd->cache_db;
464 	return (IDMAP_SUCCESS);
465 }
466 
467 /*
468  * Force next get_cache_handle to reopen.
469  * Called after DB errors.
470  */
471 void
kill_cache_handle(sqlite * db)472 kill_cache_handle(sqlite *db)
473 {
474 	idmap_tsd_t	*tsd;
475 	sqlite		*t;
476 
477 	if (db == NULL)
478 		return;
479 
480 	if ((tsd = idmap_get_tsd()) == NULL)
481 		return;
482 
483 	if ((t = tsd->cache_db) == NULL)
484 		return;
485 	assert(t == db);
486 	tsd->cache_db = NULL;
487 	(void) sqlite_close(t);
488 }
489 
490 /*
491  * Initialize cache and db
492  */
493 int
init_dbs(void)494 init_dbs(void)
495 {
496 	char *sql[4];
497 	int created, upgraded;
498 
499 	/* name-based mappings; probably OK to blow away in a pinch(?) */
500 	sql[0] = DB_INSTALL_SQL;
501 	sql[1] = DB_UPGRADE_FROM_v1_SQL;
502 	sql[2] = NULL;
503 
504 	if (init_db_instance(IDMAP_DBNAME, DB_VERSION, DB_VERSION_SQL, sql,
505 	    FAIL_IF_CORRUPT, &created, &upgraded) < 0)
506 		return (-1);
507 
508 	/* mappings, name/SID lookup cache + ephemeral IDs; OK to blow away */
509 	sql[0] = CACHE_INSTALL_SQL;
510 	sql[1] = CACHE_UPGRADE_FROM_v1_SQL;
511 	sql[2] = CACHE_UPGRADE_FROM_v2_SQL;
512 	sql[3] = NULL;
513 
514 	if (init_db_instance(IDMAP_CACHENAME, CACHE_VERSION, CACHE_VERSION_SQL,
515 	    sql, REMOVE_IF_CORRUPT, &created, &upgraded) < 0)
516 		return (-1);
517 
518 	/*
519 	 * TODO: If cache DB NOT created, get MAX PID for allocids(), eg.
520 	 * sql = "SELECT MAX(pid) as max_pid FROM idmap_cache;"
521 	 * sqlite_get_table(db, sql, &results, &nrow, NULL, &errmsg);
522 	 *
523 	 * However, the allocids() system call does not currently allow
524 	 * for this kind of initialization.  Until that's dealt with,
525 	 * use of a persistent idmap cache DB cannot work.
526 	 */
527 
528 	/* This becomes the "flush" flag for allocids() */
529 	_idmapdstate.new_eph_db = (created || upgraded) ? 1 : 0;
530 
531 	return (0);
532 }
533 
534 /*
535  * Finalize databases
536  */
537 void
fini_dbs(void)538 fini_dbs(void)
539 {
540 }
541 
542 /*
543  * This table is a listing of status codes that will be returned to the
544  * client when a SQL command fails with the corresponding error message.
545  */
546 static msg_table_t sqlmsgtable[] = {
547 	{IDMAP_ERR_U2W_NAMERULE_CONFLICT,
548 	"columns unixname, is_user, u2w_order are not unique"},
549 	{IDMAP_ERR_W2U_NAMERULE_CONFLICT,
550 	"columns winname, windomain, is_user, is_wuser, w2u_order are not"
551 	" unique"},
552 	{IDMAP_ERR_W2U_NAMERULE_CONFLICT, "Conflicting w2u namerules"},
553 	{-1, NULL}
554 };
555 
556 /*
557  * idmapd's version of string2stat to map SQLite messages to
558  * status codes
559  */
560 idmap_retcode
idmapd_string2stat(const char * msg)561 idmapd_string2stat(const char *msg)
562 {
563 	int i;
564 	for (i = 0; sqlmsgtable[i].msg; i++) {
565 		if (strcasecmp(sqlmsgtable[i].msg, msg) == 0)
566 			return (sqlmsgtable[i].retcode);
567 	}
568 	return (IDMAP_ERR_OTHER);
569 }
570 
571 /*
572  * Executes some SQL in a transaction.
573  *
574  * Returns 0 on success, -1 if it failed but the rollback succeeded, -2
575  * if the rollback failed.
576  */
577 static
578 int
sql_exec_tran_no_cb(sqlite * db,char * sql,const char * dbname,const char * while_doing)579 sql_exec_tran_no_cb(sqlite *db, char *sql, const char *dbname,
580     const char *while_doing)
581 {
582 	char		*errmsg = NULL;
583 	int		rc;
584 
585 	rc = sqlite_exec(db, "BEGIN TRANSACTION;", NULL, NULL, &errmsg);
586 	if (rc != SQLITE_OK) {
587 		idmapdlog(LOG_ERR, "Begin transaction failed (%s) "
588 		    "while %s (%s)", errmsg, while_doing, dbname);
589 		sqlite_freemem(errmsg);
590 		return (-1);
591 	}
592 
593 	rc = sqlite_exec(db, sql, NULL, NULL, &errmsg);
594 	if (rc != SQLITE_OK) {
595 		idmapdlog(LOG_ERR, "Database error (%s) while %s (%s)", errmsg,
596 		    while_doing, dbname);
597 		sqlite_freemem(errmsg);
598 		errmsg = NULL;
599 		goto rollback;
600 	}
601 
602 	rc = sqlite_exec(db, "COMMIT TRANSACTION", NULL, NULL, &errmsg);
603 	if (rc == SQLITE_OK) {
604 		sqlite_freemem(errmsg);
605 		return (0);
606 	}
607 
608 	idmapdlog(LOG_ERR, "Database commit error (%s) while s (%s)",
609 	    errmsg, while_doing, dbname);
610 	sqlite_freemem(errmsg);
611 	errmsg = NULL;
612 
613 rollback:
614 	rc = sqlite_exec(db, "ROLLBACK TRANSACTION", NULL, NULL, &errmsg);
615 	if (rc != SQLITE_OK) {
616 		idmapdlog(LOG_ERR, "Rollback failed (%s) while %s (%s)",
617 		    errmsg, while_doing, dbname);
618 		sqlite_freemem(errmsg);
619 		return (-2);
620 	}
621 	sqlite_freemem(errmsg);
622 
623 	return (-1);
624 }
625 
626 /*
627  * Execute the given SQL statment without using any callbacks
628  */
629 idmap_retcode
sql_exec_no_cb(sqlite * db,const char * dbname,char * sql)630 sql_exec_no_cb(sqlite *db, const char *dbname, char *sql)
631 {
632 	char		*errmsg = NULL;
633 	int		r;
634 	idmap_retcode	retcode;
635 
636 	r = sqlite_exec(db, sql, NULL, NULL, &errmsg);
637 	if (r != SQLITE_OK) {
638 		idmapdlog(LOG_ERR, "Database error on %s while executing %s "
639 		    "(%s)", dbname, sql, CHECK_NULL(errmsg));
640 
641 		switch (r) {
642 		case SQLITE_BUSY:
643 		case SQLITE_LOCKED:
644 			assert(0);
645 			retcode = IDMAP_ERR_INTERNAL;
646 			break;
647 
648 		case SQLITE_NOMEM:
649 			retcode = IDMAP_ERR_MEMORY;
650 			break;
651 
652 		case SQLITE_FULL:
653 			retcode = IDMAP_ERR_DB;
654 			break;
655 
656 		default:
657 			retcode = idmapd_string2stat(errmsg);
658 			break;
659 		}
660 
661 		if (errmsg != NULL)
662 			sqlite_freemem(errmsg);
663 		return (retcode);
664 	}
665 
666 	return (IDMAP_SUCCESS);
667 }
668 
669 /*
670  * Generate expression that can be used in WHERE statements.
671  * Examples:
672  * <prefix> <col>      <op> <value>   <suffix>
673  * ""       "unixuser" "="  "foo" "AND"
674  */
675 idmap_retcode
gen_sql_expr_from_rule(idmap_namerule * rule,char ** out)676 gen_sql_expr_from_rule(idmap_namerule *rule, char **out)
677 {
678 	char	*s_windomain = NULL, *s_winname = NULL;
679 	char	*s_unixname = NULL;
680 	char	*dir;
681 	char	*lower_winname;
682 	int	retcode = IDMAP_SUCCESS;
683 
684 	if (out == NULL)
685 		return (IDMAP_ERR_ARG);
686 
687 
688 	if (!EMPTY_STRING(rule->windomain)) {
689 		s_windomain =  sqlite_mprintf("AND windomain = %Q ",
690 		    rule->windomain);
691 		if (s_windomain == NULL) {
692 			retcode = IDMAP_ERR_MEMORY;
693 			goto out;
694 		}
695 	}
696 
697 	if (!EMPTY_STRING(rule->winname)) {
698 		if ((lower_winname = tolower_u8(rule->winname)) == NULL)
699 			lower_winname = rule->winname;
700 		s_winname = sqlite_mprintf(
701 		    "AND winname = %Q AND is_wuser = %d ",
702 		    lower_winname, rule->is_wuser ? 1 : 0);
703 		if (lower_winname != rule->winname)
704 			free(lower_winname);
705 		if (s_winname == NULL) {
706 			retcode = IDMAP_ERR_MEMORY;
707 			goto out;
708 		}
709 	}
710 
711 	if (!EMPTY_STRING(rule->unixname)) {
712 		s_unixname = sqlite_mprintf(
713 		    "AND unixname = %Q AND is_user = %d ",
714 		    rule->unixname, rule->is_user ? 1 : 0);
715 		if (s_unixname == NULL) {
716 			retcode = IDMAP_ERR_MEMORY;
717 			goto out;
718 		}
719 	}
720 
721 	switch (rule->direction) {
722 	case IDMAP_DIRECTION_BI:
723 		dir = "AND w2u_order > 0 AND u2w_order > 0";
724 		break;
725 	case IDMAP_DIRECTION_W2U:
726 		dir = "AND w2u_order > 0"
727 		    " AND (u2w_order = 0 OR u2w_order ISNULL)";
728 		break;
729 	case IDMAP_DIRECTION_U2W:
730 		dir = "AND u2w_order > 0"
731 		    " AND (w2u_order = 0 OR w2u_order ISNULL)";
732 		break;
733 	default:
734 		dir = "";
735 		break;
736 	}
737 
738 	*out = sqlite_mprintf("%s %s %s %s",
739 	    s_windomain ? s_windomain : "",
740 	    s_winname ? s_winname : "",
741 	    s_unixname ? s_unixname : "",
742 	    dir);
743 
744 	if (*out == NULL) {
745 		retcode = IDMAP_ERR_MEMORY;
746 		idmapdlog(LOG_ERR, "Out of memory");
747 		goto out;
748 	}
749 
750 out:
751 	if (s_windomain != NULL)
752 		sqlite_freemem(s_windomain);
753 	if (s_winname != NULL)
754 		sqlite_freemem(s_winname);
755 	if (s_unixname != NULL)
756 		sqlite_freemem(s_unixname);
757 
758 	return (retcode);
759 }
760 
761 
762 
763 /*
764  * Generate and execute SQL statement for LIST RPC calls
765  */
766 idmap_retcode
process_list_svc_sql(sqlite * db,const char * dbname,char * sql,uint64_t limit,int flag,list_svc_cb cb,void * result)767 process_list_svc_sql(sqlite *db, const char *dbname, char *sql, uint64_t limit,
768     int flag, list_svc_cb cb, void *result)
769 {
770 	list_cb_data_t	cb_data;
771 	char		*errmsg = NULL;
772 	int		r;
773 	idmap_retcode	retcode = IDMAP_ERR_INTERNAL;
774 
775 	(void) memset(&cb_data, 0, sizeof (cb_data));
776 	cb_data.result = result;
777 	cb_data.limit = limit;
778 	cb_data.flag = flag;
779 
780 
781 	r = sqlite_exec(db, sql, cb, &cb_data, &errmsg);
782 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
783 	switch (r) {
784 	case SQLITE_OK:
785 		retcode = IDMAP_SUCCESS;
786 		break;
787 
788 	default:
789 		retcode = IDMAP_ERR_INTERNAL;
790 		idmapdlog(LOG_ERR, "Database error on %s while executing "
791 		    "%s (%s)", dbname, sql, CHECK_NULL(errmsg));
792 		break;
793 	}
794 	if (errmsg != NULL)
795 		sqlite_freemem(errmsg);
796 	return (retcode);
797 }
798 
799 /*
800  * This routine is called by callbacks that process the results of
801  * LIST RPC calls to validate data and to allocate memory for
802  * the result array.
803  */
804 idmap_retcode
validate_list_cb_data(list_cb_data_t * cb_data,int argc,char ** argv,int ncol,uchar_t ** list,size_t valsize)805 validate_list_cb_data(list_cb_data_t *cb_data, int argc, char **argv,
806     int ncol, uchar_t **list, size_t valsize)
807 {
808 	size_t	nsize;
809 	void	*tmplist;
810 
811 	if (cb_data->limit > 0 && cb_data->next == cb_data->limit)
812 		return (IDMAP_NEXT);
813 
814 	if (argc < ncol || argv == NULL) {
815 		idmapdlog(LOG_ERR, "Invalid data");
816 		return (IDMAP_ERR_INTERNAL);
817 	}
818 
819 	/* alloc in bulk to reduce number of reallocs */
820 	if (cb_data->next >= cb_data->len) {
821 		nsize = (cb_data->len + SIZE_INCR) * valsize;
822 		tmplist = realloc(*list, nsize);
823 		if (tmplist == NULL) {
824 			idmapdlog(LOG_ERR, "Out of memory");
825 			return (IDMAP_ERR_MEMORY);
826 		}
827 		*list = tmplist;
828 		(void) memset(*list + (cb_data->len * valsize), 0,
829 		    SIZE_INCR * valsize);
830 		cb_data->len += SIZE_INCR;
831 	}
832 	return (IDMAP_SUCCESS);
833 }
834 
835 static
836 idmap_retcode
get_namerule_order(char * winname,char * windomain,char * unixname,int direction,int is_diagonal,int * w2u_order,int * u2w_order)837 get_namerule_order(char *winname, char *windomain, char *unixname,
838     int direction, int is_diagonal, int *w2u_order, int *u2w_order)
839 {
840 	*w2u_order = 0;
841 	*u2w_order = 0;
842 
843 	/*
844 	 * Windows to UNIX lookup order:
845 	 *  1. winname@domain (or winname) to ""
846 	 *  2. winname@domain (or winname) to unixname
847 	 *  3. winname@* to ""
848 	 *  4. winname@* to unixname
849 	 *  5. *@domain (or *) to *
850 	 *  6. *@domain (or *) to ""
851 	 *  7. *@domain (or *) to unixname
852 	 *  8. *@* to *
853 	 *  9. *@* to ""
854 	 * 10. *@* to unixname
855 	 *
856 	 * winname is a special case of winname@domain when domain is the
857 	 * default domain. Similarly * is a special case of *@domain when
858 	 * domain is the default domain.
859 	 *
860 	 * Note that "" has priority over specific names because "" inhibits
861 	 * mappings and traditionally deny rules always had higher priority.
862 	 */
863 	if (direction != IDMAP_DIRECTION_U2W) {
864 		/* bi-directional or from windows to unix */
865 		if (winname == NULL)
866 			return (IDMAP_ERR_W2U_NAMERULE);
867 		else if (unixname == NULL)
868 			return (IDMAP_ERR_W2U_NAMERULE);
869 		else if (EMPTY_NAME(winname))
870 			return (IDMAP_ERR_W2U_NAMERULE);
871 		else if (*winname == '*' && windomain && *windomain == '*') {
872 			if (*unixname == '*')
873 				*w2u_order = 8;
874 			else if (EMPTY_NAME(unixname))
875 				*w2u_order = 9;
876 			else /* unixname == name */
877 				*w2u_order = 10;
878 		} else if (*winname == '*') {
879 			if (*unixname == '*')
880 				*w2u_order = 5;
881 			else if (EMPTY_NAME(unixname))
882 				*w2u_order = 6;
883 			else /* name */
884 				*w2u_order = 7;
885 		} else if (windomain != NULL && *windomain == '*') {
886 			/* winname == name */
887 			if (*unixname == '*')
888 				return (IDMAP_ERR_W2U_NAMERULE);
889 			else if (EMPTY_NAME(unixname))
890 				*w2u_order = 3;
891 			else /* name */
892 				*w2u_order = 4;
893 		} else  {
894 			/* winname == name && windomain == null or name */
895 			if (*unixname == '*')
896 				return (IDMAP_ERR_W2U_NAMERULE);
897 			else if (EMPTY_NAME(unixname))
898 				*w2u_order = 1;
899 			else /* name */
900 				*w2u_order = 2;
901 		}
902 
903 	}
904 
905 	/*
906 	 * 1. unixname to "", non-diagonal
907 	 * 2. unixname to winname@domain (or winname), non-diagonal
908 	 * 3. unixname to "", diagonal
909 	 * 4. unixname to winname@domain (or winname), diagonal
910 	 * 5. * to *@domain (or *), non-diagonal
911 	 * 5. * to *@domain (or *), diagonal
912 	 * 7. * to ""
913 	 * 8. * to winname@domain (or winname)
914 	 * 9. * to "", non-diagonal
915 	 * 10. * to winname@domain (or winname), diagonal
916 	 */
917 	if (direction != IDMAP_DIRECTION_W2U) {
918 		int diagonal = is_diagonal ? 1 : 0;
919 
920 		/* bi-directional or from unix to windows */
921 		if (unixname == NULL || EMPTY_NAME(unixname))
922 			return (IDMAP_ERR_U2W_NAMERULE);
923 		else if (winname == NULL)
924 			return (IDMAP_ERR_U2W_NAMERULE);
925 		else if (windomain != NULL && *windomain == '*')
926 			return (IDMAP_ERR_U2W_NAMERULE);
927 		else if (*unixname == '*') {
928 			if (*winname == '*')
929 				*u2w_order = 5 + diagonal;
930 			else if (EMPTY_NAME(winname))
931 				*u2w_order = 7 + 2 * diagonal;
932 			else
933 				*u2w_order = 8 + 2 * diagonal;
934 		} else {
935 			if (*winname == '*')
936 				return (IDMAP_ERR_U2W_NAMERULE);
937 			else if (EMPTY_NAME(winname))
938 				*u2w_order = 1 + 2 * diagonal;
939 			else
940 				*u2w_order = 2 + 2 * diagonal;
941 		}
942 	}
943 	return (IDMAP_SUCCESS);
944 }
945 
946 /*
947  * Generate and execute SQL statement to add name-based mapping rule
948  */
949 idmap_retcode
add_namerule(sqlite * db,idmap_namerule * rule)950 add_namerule(sqlite *db, idmap_namerule *rule)
951 {
952 	char		*sql = NULL;
953 	idmap_stat	retcode;
954 	char		*dom = NULL;
955 	char		*name;
956 	int		w2u_order, u2w_order;
957 	char		w2ubuf[11], u2wbuf[11];
958 	char		*canonname = NULL;
959 	char		*canondomain = NULL;
960 
961 	retcode = get_namerule_order(rule->winname, rule->windomain,
962 	    rule->unixname, rule->direction,
963 	    rule->is_user == rule->is_wuser ? 0 : 1, &w2u_order, &u2w_order);
964 	if (retcode != IDMAP_SUCCESS)
965 		goto out;
966 
967 	if (w2u_order)
968 		(void) snprintf(w2ubuf, sizeof (w2ubuf), "%d", w2u_order);
969 	if (u2w_order)
970 		(void) snprintf(u2wbuf, sizeof (u2wbuf), "%d", u2w_order);
971 
972 	/*
973 	 * For the triggers on namerules table to work correctly:
974 	 * 1) Use NULL instead of 0 for w2u_order and u2w_order
975 	 * 2) Use "" instead of NULL for "no domain"
976 	 */
977 
978 	name = rule->winname;
979 	dom = rule->windomain;
980 
981 	RDLOCK_CONFIG();
982 	if (lookup_wksids_name2sid(name, dom,
983 	    &canonname, &canondomain,
984 	    NULL, NULL, NULL) == IDMAP_SUCCESS) {
985 		name = canonname;
986 		dom = canondomain;
987 	} else if (EMPTY_STRING(dom)) {
988 		if (_idmapdstate.cfg->pgcfg.default_domain)
989 			dom = _idmapdstate.cfg->pgcfg.default_domain;
990 		else
991 			dom = "";
992 	}
993 	sql = sqlite_mprintf("INSERT into namerules "
994 	    "(is_user, is_wuser, windomain, winname_display, is_nt4, "
995 	    "unixname, w2u_order, u2w_order) "
996 	    "VALUES(%d, %d, %Q, %Q, %d, %Q, %q, %q);",
997 	    rule->is_user ? 1 : 0, rule->is_wuser ? 1 : 0, dom,
998 	    name, rule->is_nt4 ? 1 : 0, rule->unixname,
999 	    w2u_order ? w2ubuf : NULL, u2w_order ? u2wbuf : NULL);
1000 	UNLOCK_CONFIG();
1001 
1002 	if (sql == NULL) {
1003 		retcode = IDMAP_ERR_INTERNAL;
1004 		idmapdlog(LOG_ERR, "Out of memory");
1005 		goto out;
1006 	}
1007 
1008 	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, sql);
1009 
1010 	if (retcode == IDMAP_ERR_OTHER)
1011 		retcode = IDMAP_ERR_CFG;
1012 
1013 out:
1014 	free(canonname);
1015 	free(canondomain);
1016 	if (sql != NULL)
1017 		sqlite_freemem(sql);
1018 	return (retcode);
1019 }
1020 
1021 /*
1022  * Flush name-based mapping rules
1023  */
1024 idmap_retcode
flush_namerules(sqlite * db)1025 flush_namerules(sqlite *db)
1026 {
1027 	idmap_stat	retcode;
1028 
1029 	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, "DELETE FROM namerules;");
1030 
1031 	return (retcode);
1032 }
1033 
1034 /*
1035  * Generate and execute SQL statement to remove a name-based mapping rule
1036  */
1037 idmap_retcode
rm_namerule(sqlite * db,idmap_namerule * rule)1038 rm_namerule(sqlite *db, idmap_namerule *rule)
1039 {
1040 	char		*sql = NULL;
1041 	idmap_stat	retcode;
1042 	char		*expr = NULL;
1043 
1044 	if (rule->direction < 0 && EMPTY_STRING(rule->windomain) &&
1045 	    EMPTY_STRING(rule->winname) && EMPTY_STRING(rule->unixname))
1046 		return (IDMAP_SUCCESS);
1047 
1048 	retcode = gen_sql_expr_from_rule(rule, &expr);
1049 	if (retcode != IDMAP_SUCCESS)
1050 		goto out;
1051 
1052 	sql = sqlite_mprintf("DELETE FROM namerules WHERE 1 %s;", expr);
1053 
1054 	if (sql == NULL) {
1055 		retcode = IDMAP_ERR_INTERNAL;
1056 		idmapdlog(LOG_ERR, "Out of memory");
1057 		goto out;
1058 	}
1059 
1060 
1061 	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, sql);
1062 
1063 out:
1064 	if (expr != NULL)
1065 		sqlite_freemem(expr);
1066 	if (sql != NULL)
1067 		sqlite_freemem(sql);
1068 	return (retcode);
1069 }
1070 
1071 /*
1072  * Compile the given SQL query and step just once.
1073  *
1074  * Input:
1075  * db  - db handle
1076  * sql - SQL statement
1077  *
1078  * Output:
1079  * vm     -  virtual SQL machine
1080  * ncol   - number of columns in the result
1081  * values - column values
1082  *
1083  * Return values:
1084  * IDMAP_SUCCESS
1085  * IDMAP_ERR_NOTFOUND
1086  * IDMAP_ERR_INTERNAL
1087  */
1088 
1089 static
1090 idmap_retcode
sql_compile_n_step_once(sqlite * db,char * sql,sqlite_vm ** vm,int * ncol,int reqcol,const char *** values)1091 sql_compile_n_step_once(sqlite *db, char *sql, sqlite_vm **vm, int *ncol,
1092     int reqcol, const char ***values)
1093 {
1094 	char		*errmsg = NULL;
1095 	int		r;
1096 
1097 	if ((r = sqlite_compile(db, sql, NULL, vm, &errmsg)) != SQLITE_OK) {
1098 		idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
1099 		    CHECK_NULL(errmsg));
1100 		sqlite_freemem(errmsg);
1101 		return (IDMAP_ERR_INTERNAL);
1102 	}
1103 
1104 	r = sqlite_step(*vm, ncol, values, NULL);
1105 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
1106 
1107 	if (r == SQLITE_ROW) {
1108 		if (ncol != NULL && *ncol < reqcol) {
1109 			(void) sqlite_finalize(*vm, NULL);
1110 			*vm = NULL;
1111 			return (IDMAP_ERR_INTERNAL);
1112 		}
1113 		/* Caller will call finalize after using the results */
1114 		return (IDMAP_SUCCESS);
1115 	} else if (r == SQLITE_DONE) {
1116 		(void) sqlite_finalize(*vm, NULL);
1117 		*vm = NULL;
1118 		return (IDMAP_ERR_NOTFOUND);
1119 	}
1120 
1121 	(void) sqlite_finalize(*vm, &errmsg);
1122 	*vm = NULL;
1123 	idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
1124 	    CHECK_NULL(errmsg));
1125 	sqlite_freemem(errmsg);
1126 	return (IDMAP_ERR_INTERNAL);
1127 }
1128 
1129 /*
1130  * Load config in the state.
1131  *
1132  * nm_siduid and nm_sidgid fields:
1133  * state->nm_siduid represents mode used by sid2uid and uid2sid
1134  * requests for directory-based name mappings. Similarly,
1135  * state->nm_sidgid represents mode used by sid2gid and gid2sid
1136  * requests.
1137  *
1138  * sid2uid/uid2sid:
1139  * none       -> directory_based_mapping != DIRECTORY_MAPPING_NAME
1140  * AD-mode    -> !nldap_winname_attr && ad_unixuser_attr
1141  * nldap-mode -> nldap_winname_attr && !ad_unixuser_attr
1142  * mixed-mode -> nldap_winname_attr && ad_unixuser_attr
1143  *
1144  * sid2gid/gid2sid:
1145  * none       -> directory_based_mapping != DIRECTORY_MAPPING_NAME
1146  * AD-mode    -> !nldap_winname_attr && ad_unixgroup_attr
1147  * nldap-mode -> nldap_winname_attr && !ad_unixgroup_attr
1148  * mixed-mode -> nldap_winname_attr && ad_unixgroup_attr
1149  */
1150 idmap_retcode
load_cfg_in_state(lookup_state_t * state)1151 load_cfg_in_state(lookup_state_t *state)
1152 {
1153 	state->nm_siduid = IDMAP_NM_NONE;
1154 	state->nm_sidgid = IDMAP_NM_NONE;
1155 	RDLOCK_CONFIG();
1156 
1157 	state->eph_map_unres_sids = 0;
1158 	if (_idmapdstate.cfg->pgcfg.eph_map_unres_sids)
1159 		state->eph_map_unres_sids = 1;
1160 
1161 	state->id_cache_timeout =
1162 	    _idmapdstate.cfg->pgcfg.id_cache_timeout;
1163 	state->name_cache_timeout =
1164 	    _idmapdstate.cfg->pgcfg.name_cache_timeout;
1165 
1166 	state->directory_based_mapping =
1167 	    _idmapdstate.cfg->pgcfg.directory_based_mapping;
1168 
1169 	if (_idmapdstate.cfg->pgcfg.default_domain != NULL) {
1170 		state->defdom =
1171 		    strdup(_idmapdstate.cfg->pgcfg.default_domain);
1172 		if (state->defdom == NULL) {
1173 			UNLOCK_CONFIG();
1174 			return (IDMAP_ERR_MEMORY);
1175 		}
1176 	} else {
1177 		UNLOCK_CONFIG();
1178 		return (IDMAP_SUCCESS);
1179 	}
1180 
1181 	if (_idmapdstate.cfg->pgcfg.directory_based_mapping !=
1182 	    DIRECTORY_MAPPING_NAME) {
1183 		UNLOCK_CONFIG();
1184 		return (IDMAP_SUCCESS);
1185 	}
1186 
1187 	if (_idmapdstate.cfg->pgcfg.nldap_winname_attr != NULL) {
1188 		state->nm_siduid =
1189 		    (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL)
1190 		    ? IDMAP_NM_MIXED : IDMAP_NM_NLDAP;
1191 		state->nm_sidgid =
1192 		    (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL)
1193 		    ? IDMAP_NM_MIXED : IDMAP_NM_NLDAP;
1194 	} else {
1195 		state->nm_siduid =
1196 		    (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL)
1197 		    ? IDMAP_NM_AD : IDMAP_NM_NONE;
1198 		state->nm_sidgid =
1199 		    (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL)
1200 		    ? IDMAP_NM_AD : IDMAP_NM_NONE;
1201 	}
1202 	if (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL) {
1203 		state->ad_unixuser_attr =
1204 		    strdup(_idmapdstate.cfg->pgcfg.ad_unixuser_attr);
1205 		if (state->ad_unixuser_attr == NULL) {
1206 			UNLOCK_CONFIG();
1207 			return (IDMAP_ERR_MEMORY);
1208 		}
1209 	}
1210 	if (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL) {
1211 		state->ad_unixgroup_attr =
1212 		    strdup(_idmapdstate.cfg->pgcfg.ad_unixgroup_attr);
1213 		if (state->ad_unixgroup_attr == NULL) {
1214 			UNLOCK_CONFIG();
1215 			return (IDMAP_ERR_MEMORY);
1216 		}
1217 	}
1218 	if (_idmapdstate.cfg->pgcfg.nldap_winname_attr != NULL) {
1219 		state->nldap_winname_attr =
1220 		    strdup(_idmapdstate.cfg->pgcfg.nldap_winname_attr);
1221 		if (state->nldap_winname_attr == NULL) {
1222 			UNLOCK_CONFIG();
1223 			return (IDMAP_ERR_MEMORY);
1224 		}
1225 	}
1226 	UNLOCK_CONFIG();
1227 	return (IDMAP_SUCCESS);
1228 }
1229 
1230 /*
1231  * Set the rule with specified values.
1232  * All the strings are copied.
1233  */
1234 static void
idmap_namerule_set(idmap_namerule * rule,const char * windomain,const char * winname,const char * unixname,boolean_t is_user,boolean_t is_wuser,boolean_t is_nt4,int direction)1235 idmap_namerule_set(idmap_namerule *rule, const char *windomain,
1236     const char *winname, const char *unixname, boolean_t is_user,
1237     boolean_t is_wuser, boolean_t is_nt4, int direction)
1238 {
1239 	/*
1240 	 * Only update if they differ because we have to free
1241 	 * and duplicate the strings
1242 	 */
1243 	if (rule->windomain == NULL || windomain == NULL ||
1244 	    strcmp(rule->windomain, windomain) != 0) {
1245 		if (rule->windomain != NULL) {
1246 			free(rule->windomain);
1247 			rule->windomain = NULL;
1248 		}
1249 		if (windomain != NULL)
1250 			rule->windomain = strdup(windomain);
1251 	}
1252 
1253 	if (rule->winname == NULL || winname == NULL ||
1254 	    strcmp(rule->winname, winname) != 0) {
1255 		if (rule->winname != NULL) {
1256 			free(rule->winname);
1257 			rule->winname = NULL;
1258 		}
1259 		if (winname != NULL)
1260 			rule->winname = strdup(winname);
1261 	}
1262 
1263 	if (rule->unixname == NULL || unixname == NULL ||
1264 	    strcmp(rule->unixname, unixname) != 0) {
1265 		if (rule->unixname != NULL) {
1266 			free(rule->unixname);
1267 			rule->unixname = NULL;
1268 		}
1269 		if (unixname != NULL)
1270 			rule->unixname = strdup(unixname);
1271 	}
1272 
1273 	rule->is_user = is_user;
1274 	rule->is_wuser = is_wuser;
1275 	rule->is_nt4 = is_nt4;
1276 	rule->direction = direction;
1277 }
1278 
1279 /*
1280  * Lookup well-known SIDs table either by winname or by SID.
1281  *
1282  * If the given winname or SID is a well-known SID then we set is_wksid
1283  * variable and then proceed to see if the SID has a hard mapping to
1284  * a particular UID/GID (Ex: Creator Owner/Creator Group mapped to
1285  * fixed ephemeral ids). The direction flag indicates whether we have
1286  * a mapping; UNDEF indicates that we do not.
1287  *
1288  * If we find a mapping then we return success, except for the
1289  * special case of IDMAP_SENTINEL_PID which indicates an inhibited mapping.
1290  *
1291  * If we find a matching entry, but no mapping, we supply SID, name, and type
1292  * information and return "not found".  Higher layers will probably
1293  * do ephemeral mapping.
1294  *
1295  * If we do not find a match, we return "not found" and leave the question
1296  * to higher layers.
1297  */
1298 static
1299 idmap_retcode
lookup_wksids_sid2pid(idmap_mapping * req,idmap_id_res * res,int * is_wksid)1300 lookup_wksids_sid2pid(idmap_mapping *req, idmap_id_res *res, int *is_wksid)
1301 {
1302 	const wksids_table_t *wksid;
1303 
1304 	*is_wksid = 0;
1305 
1306 	assert(req->id1.idmap_id_u.sid.prefix != NULL ||
1307 	    req->id1name != NULL);
1308 
1309 	if (req->id1.idmap_id_u.sid.prefix != NULL) {
1310 		wksid = find_wksid_by_sid(req->id1.idmap_id_u.sid.prefix,
1311 		    req->id1.idmap_id_u.sid.rid, res->id.idtype);
1312 	} else {
1313 		wksid = find_wksid_by_name(req->id1name, req->id1domain,
1314 		    res->id.idtype);
1315 	}
1316 	if (wksid == NULL)
1317 		return (IDMAP_ERR_NOTFOUND);
1318 
1319 	/* Found matching entry. */
1320 
1321 	/* Fill in name if it was not already there. */
1322 	if (req->id1name == NULL) {
1323 		req->id1name = strdup(wksid->winname);
1324 		if (req->id1name == NULL)
1325 			return (IDMAP_ERR_MEMORY);
1326 	}
1327 
1328 	/* Fill in SID if it was not already there */
1329 	if (req->id1.idmap_id_u.sid.prefix == NULL) {
1330 		if (wksid->sidprefix != NULL) {
1331 			req->id1.idmap_id_u.sid.prefix =
1332 			    strdup(wksid->sidprefix);
1333 		} else {
1334 			RDLOCK_CONFIG();
1335 			req->id1.idmap_id_u.sid.prefix =
1336 			    strdup(_idmapdstate.cfg->pgcfg.machine_sid);
1337 			UNLOCK_CONFIG();
1338 		}
1339 		if (req->id1.idmap_id_u.sid.prefix == NULL)
1340 			return (IDMAP_ERR_MEMORY);
1341 		req->id1.idmap_id_u.sid.rid = wksid->rid;
1342 	}
1343 
1344 	/* Fill in the canonical domain if not already there */
1345 	if (req->id1domain == NULL) {
1346 		const char *dom;
1347 
1348 		RDLOCK_CONFIG();
1349 		if (wksid->domain != NULL)
1350 			dom = wksid->domain;
1351 		else
1352 			dom = _idmapdstate.hostname;
1353 		req->id1domain = strdup(dom);
1354 		UNLOCK_CONFIG();
1355 		if (req->id1domain == NULL)
1356 			return (IDMAP_ERR_MEMORY);
1357 	}
1358 
1359 	*is_wksid = 1;
1360 	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
1361 
1362 	req->id1.idtype = wksid->is_wuser ? IDMAP_USID : IDMAP_GSID;
1363 
1364 	if (res->id.idtype == IDMAP_POSIXID) {
1365 		res->id.idtype = wksid->is_wuser ? IDMAP_UID : IDMAP_GID;
1366 	}
1367 
1368 	if (wksid->direction == IDMAP_DIRECTION_UNDEF) {
1369 		/*
1370 		 * We don't have a mapping
1371 		 * (But note that we may have supplied SID, name, or type
1372 		 * information.)
1373 		 */
1374 		return (IDMAP_ERR_NOTFOUND);
1375 	}
1376 
1377 	/*
1378 	 * We have an explicit mapping.
1379 	 */
1380 	if (wksid->pid == IDMAP_SENTINEL_PID) {
1381 		/*
1382 		 * ... which is that mapping is inhibited.
1383 		 */
1384 		return (IDMAP_ERR_NOMAPPING);
1385 	}
1386 
1387 	switch (res->id.idtype) {
1388 	case IDMAP_UID:
1389 		res->id.idmap_id_u.uid = wksid->pid;
1390 		break;
1391 	case IDMAP_GID:
1392 		res->id.idmap_id_u.gid = wksid->pid;
1393 		break;
1394 	default:
1395 		/* IDMAP_POSIXID is eliminated above */
1396 		return (IDMAP_ERR_NOTSUPPORTED);
1397 	}
1398 
1399 	res->direction = wksid->direction;
1400 	res->info.how.map_type = IDMAP_MAP_TYPE_KNOWN_SID;
1401 	res->info.src = IDMAP_MAP_SRC_HARD_CODED;
1402 	return (IDMAP_SUCCESS);
1403 }
1404 
1405 
1406 /*
1407  * Look for an entry mapping a PID to a SID.
1408  *
1409  * Note that direction=UNDEF entries do not specify a mapping,
1410  * and that IDMAP_SENTINEL_PID entries represent either an inhibited
1411  * mapping or an ephemeral mapping.  We don't handle either here;
1412  * they are filtered out by find_wksid_by_pid.
1413  */
1414 static
1415 idmap_retcode
lookup_wksids_pid2sid(idmap_mapping * req,idmap_id_res * res,int is_user)1416 lookup_wksids_pid2sid(idmap_mapping *req, idmap_id_res *res, int is_user)
1417 {
1418 	const wksids_table_t *wksid;
1419 
1420 	wksid = find_wksid_by_pid(req->id1.idmap_id_u.uid, is_user);
1421 	if (wksid == NULL)
1422 		return (IDMAP_ERR_NOTFOUND);
1423 
1424 	if (res->id.idtype == IDMAP_SID) {
1425 		res->id.idtype = wksid->is_wuser ? IDMAP_USID : IDMAP_GSID;
1426 	}
1427 	res->id.idmap_id_u.sid.rid = wksid->rid;
1428 
1429 	if (wksid->sidprefix != NULL) {
1430 		res->id.idmap_id_u.sid.prefix =
1431 		    strdup(wksid->sidprefix);
1432 	} else {
1433 		RDLOCK_CONFIG();
1434 		res->id.idmap_id_u.sid.prefix =
1435 		    strdup(_idmapdstate.cfg->pgcfg.machine_sid);
1436 		UNLOCK_CONFIG();
1437 	}
1438 
1439 	if (res->id.idmap_id_u.sid.prefix == NULL) {
1440 		idmapdlog(LOG_ERR, "Out of memory");
1441 		return (IDMAP_ERR_MEMORY);
1442 	}
1443 
1444 	/* Fill in name if it was not already there. */
1445 	if (req->id2name == NULL) {
1446 		req->id2name = strdup(wksid->winname);
1447 		if (req->id2name == NULL)
1448 			return (IDMAP_ERR_MEMORY);
1449 	}
1450 
1451 	/* Fill in the canonical domain if not already there */
1452 	if (req->id2domain == NULL) {
1453 		const char *dom;
1454 
1455 		RDLOCK_CONFIG();
1456 		if (wksid->domain != NULL)
1457 			dom = wksid->domain;
1458 		else
1459 			dom = _idmapdstate.hostname;
1460 		req->id2domain = strdup(dom);
1461 		UNLOCK_CONFIG();
1462 		if (req->id2domain == NULL)
1463 			return (IDMAP_ERR_MEMORY);
1464 	}
1465 
1466 	res->direction = wksid->direction;
1467 	res->info.how.map_type = IDMAP_MAP_TYPE_KNOWN_SID;
1468 	res->info.src = IDMAP_MAP_SRC_HARD_CODED;
1469 	return (IDMAP_SUCCESS);
1470 }
1471 
1472 /*
1473  * Look up a name in the wksids list, matching name and, if supplied, domain,
1474  * and extract data.
1475  *
1476  * Given:
1477  * name		Windows user name
1478  * domain	Windows domain name (or NULL)
1479  *
1480  * Return:  Error code
1481  *
1482  * *canonname	canonical name (if canonname non-NULL) [1]
1483  * *canondomain	canonical domain (if canondomain non-NULL) [1]
1484  * *sidprefix	SID prefix (if sidprefix non-NULL) [1]
1485  * *rid		RID (if rid non-NULL) [2]
1486  * *type	Type (if type non-NULL) [2]
1487  *
1488  * [1] malloc'ed, NULL on error
1489  * [2] Undefined on error
1490  */
1491 idmap_retcode
lookup_wksids_name2sid(const char * name,const char * domain,char ** canonname,char ** canondomain,char ** sidprefix,idmap_rid_t * rid,idmap_id_type * type)1492 lookup_wksids_name2sid(
1493     const char *name,
1494     const char *domain,
1495     char **canonname,
1496     char **canondomain,
1497     char **sidprefix,
1498     idmap_rid_t *rid,
1499     idmap_id_type *type)
1500 {
1501 	const wksids_table_t *wksid;
1502 
1503 	if (sidprefix != NULL)
1504 		*sidprefix = NULL;
1505 	if (canonname != NULL)
1506 		*canonname = NULL;
1507 	if (canondomain != NULL)
1508 		*canondomain = NULL;
1509 
1510 	wksid = find_wksid_by_name(name, domain, IDMAP_POSIXID);
1511 	if (wksid == NULL)
1512 		return (IDMAP_ERR_NOTFOUND);
1513 
1514 	if (sidprefix != NULL) {
1515 		if (wksid->sidprefix != NULL) {
1516 			*sidprefix = strdup(wksid->sidprefix);
1517 		} else {
1518 			RDLOCK_CONFIG();
1519 			*sidprefix = strdup(
1520 			    _idmapdstate.cfg->pgcfg.machine_sid);
1521 			UNLOCK_CONFIG();
1522 		}
1523 		if (*sidprefix == NULL)
1524 			goto nomem;
1525 	}
1526 
1527 	if (rid != NULL)
1528 		*rid = wksid->rid;
1529 
1530 	if (canonname != NULL) {
1531 		*canonname = strdup(wksid->winname);
1532 		if (*canonname == NULL)
1533 			goto nomem;
1534 	}
1535 
1536 	if (canondomain != NULL) {
1537 		if (wksid->domain != NULL) {
1538 			*canondomain = strdup(wksid->domain);
1539 		} else {
1540 			RDLOCK_CONFIG();
1541 			*canondomain = strdup(_idmapdstate.hostname);
1542 			UNLOCK_CONFIG();
1543 		}
1544 		if (*canondomain == NULL)
1545 			goto nomem;
1546 	}
1547 
1548 	if (type != NULL)
1549 		*type = (wksid->is_wuser) ?
1550 		    IDMAP_USID : IDMAP_GSID;
1551 
1552 	return (IDMAP_SUCCESS);
1553 
1554 nomem:
1555 	idmapdlog(LOG_ERR, "Out of memory");
1556 
1557 	if (sidprefix != NULL) {
1558 		free(*sidprefix);
1559 		*sidprefix = NULL;
1560 	}
1561 
1562 	if (canonname != NULL) {
1563 		free(*canonname);
1564 		*canonname = NULL;
1565 	}
1566 
1567 	if (canondomain != NULL) {
1568 		free(*canondomain);
1569 		*canondomain = NULL;
1570 	}
1571 
1572 	return (IDMAP_ERR_MEMORY);
1573 }
1574 
1575 static
1576 idmap_retcode
lookup_cache_sid2pid(sqlite * cache,idmap_mapping * req,idmap_id_res * res)1577 lookup_cache_sid2pid(sqlite *cache, idmap_mapping *req, idmap_id_res *res)
1578 {
1579 	char		*end;
1580 	char		*sql = NULL;
1581 	const char	**values;
1582 	sqlite_vm	*vm = NULL;
1583 	int		ncol, is_user;
1584 	uid_t		pid;
1585 	time_t		curtime, exp;
1586 	idmap_retcode	retcode;
1587 	char		*is_user_string, *lower_name;
1588 
1589 	/* Current time */
1590 	errno = 0;
1591 	if ((curtime = time(NULL)) == (time_t)-1) {
1592 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
1593 		    strerror(errno));
1594 		retcode = IDMAP_ERR_INTERNAL;
1595 		goto out;
1596 	}
1597 
1598 	switch (res->id.idtype) {
1599 	case IDMAP_UID:
1600 		is_user_string = "1";
1601 		break;
1602 	case IDMAP_GID:
1603 		is_user_string = "0";
1604 		break;
1605 	case IDMAP_POSIXID:
1606 		/* the non-diagonal mapping */
1607 		is_user_string = "is_wuser";
1608 		break;
1609 	default:
1610 		retcode = IDMAP_ERR_NOTSUPPORTED;
1611 		goto out;
1612 	}
1613 
1614 	/* SQL to lookup the cache */
1615 
1616 	if (req->id1.idmap_id_u.sid.prefix != NULL) {
1617 		sql = sqlite_mprintf("SELECT pid, is_user, expiration, "
1618 		    "unixname, u2w, is_wuser, "
1619 		    "map_type, map_dn, map_attr, map_value, "
1620 		    "map_windomain, map_winname, map_unixname, map_is_nt4 "
1621 		    "FROM idmap_cache WHERE is_user = %s AND "
1622 		    "sidprefix = %Q AND rid = %u AND w2u = 1 AND "
1623 		    "(pid >= 2147483648 OR "
1624 		    "(expiration = 0 OR expiration ISNULL OR "
1625 		    "expiration > %d));",
1626 		    is_user_string, req->id1.idmap_id_u.sid.prefix,
1627 		    req->id1.idmap_id_u.sid.rid, curtime);
1628 	} else if (req->id1name != NULL) {
1629 		if ((lower_name = tolower_u8(req->id1name)) == NULL)
1630 			lower_name = req->id1name;
1631 		sql = sqlite_mprintf("SELECT pid, is_user, expiration, "
1632 		    "unixname, u2w, is_wuser, "
1633 		    "map_type, map_dn, map_attr, map_value, "
1634 		    "map_windomain, map_winname, map_unixname, map_is_nt4 "
1635 		    "FROM idmap_cache WHERE is_user = %s AND "
1636 		    "winname = %Q AND windomain = %Q AND w2u = 1 AND "
1637 		    "(pid >= 2147483648 OR "
1638 		    "(expiration = 0 OR expiration ISNULL OR "
1639 		    "expiration > %d));",
1640 		    is_user_string, lower_name, req->id1domain,
1641 		    curtime);
1642 		if (lower_name != req->id1name)
1643 			free(lower_name);
1644 	} else {
1645 		retcode = IDMAP_ERR_ARG;
1646 		goto out;
1647 	}
1648 	if (sql == NULL) {
1649 		idmapdlog(LOG_ERR, "Out of memory");
1650 		retcode = IDMAP_ERR_MEMORY;
1651 		goto out;
1652 	}
1653 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol,
1654 	    14, &values);
1655 	sqlite_freemem(sql);
1656 
1657 	if (retcode == IDMAP_ERR_NOTFOUND) {
1658 		goto out;
1659 	} else if (retcode == IDMAP_SUCCESS) {
1660 		/* sanity checks */
1661 		if (values[0] == NULL || values[1] == NULL) {
1662 			retcode = IDMAP_ERR_CACHE;
1663 			goto out;
1664 		}
1665 
1666 		pid = strtoul(values[0], &end, 10);
1667 		is_user = strncmp(values[1], "0", 2) ? 1 : 0;
1668 
1669 		if (is_user) {
1670 			res->id.idtype = IDMAP_UID;
1671 			res->id.idmap_id_u.uid = pid;
1672 		} else {
1673 			res->id.idtype = IDMAP_GID;
1674 			res->id.idmap_id_u.gid = pid;
1675 		}
1676 
1677 		/*
1678 		 * We may have an expired ephemeral mapping. Consider
1679 		 * the expired entry as valid if we are not going to
1680 		 * perform name-based mapping. But do not renew the
1681 		 * expiration.
1682 		 * If we will be doing name-based mapping then store the
1683 		 * ephemeral pid in the result so that we can use it
1684 		 * if we end up doing dynamic mapping again.
1685 		 */
1686 		if (!DO_NOT_ALLOC_NEW_ID_MAPPING(req) &&
1687 		    !AVOID_NAMESERVICE(req) &&
1688 		    IDMAP_ID_IS_EPHEMERAL(pid) && values[2] != NULL) {
1689 			exp = strtoll(values[2], &end, 10);
1690 			if (exp && exp <= curtime) {
1691 				/* Store the ephemeral pid */
1692 				res->direction = IDMAP_DIRECTION_BI;
1693 				req->direction |= is_user
1694 				    ? _IDMAP_F_EXP_EPH_UID
1695 				    : _IDMAP_F_EXP_EPH_GID;
1696 				retcode = IDMAP_ERR_NOTFOUND;
1697 			}
1698 		}
1699 	}
1700 
1701 out:
1702 	if (retcode == IDMAP_SUCCESS) {
1703 		if (values[4] != NULL)
1704 			res->direction =
1705 			    (strtol(values[4], &end, 10) == 0)?
1706 			    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
1707 		else
1708 			res->direction = IDMAP_DIRECTION_W2U;
1709 
1710 		if (values[3] != NULL) {
1711 			if (req->id2name != NULL)
1712 				free(req->id2name);
1713 			req->id2name = strdup(values[3]);
1714 			if (req->id2name == NULL) {
1715 				idmapdlog(LOG_ERR, "Out of memory");
1716 				retcode = IDMAP_ERR_MEMORY;
1717 			}
1718 		}
1719 
1720 		req->id1.idtype = strncmp(values[5], "0", 2) ?
1721 		    IDMAP_USID : IDMAP_GSID;
1722 
1723 		if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
1724 			res->info.src = IDMAP_MAP_SRC_CACHE;
1725 			res->info.how.map_type = strtoul(values[6], &end, 10);
1726 			switch (res->info.how.map_type) {
1727 			case IDMAP_MAP_TYPE_DS_AD:
1728 				res->info.how.idmap_how_u.ad.dn =
1729 				    strdup(values[7]);
1730 				res->info.how.idmap_how_u.ad.attr =
1731 				    strdup(values[8]);
1732 				res->info.how.idmap_how_u.ad.value =
1733 				    strdup(values[9]);
1734 				break;
1735 
1736 			case IDMAP_MAP_TYPE_DS_NLDAP:
1737 				res->info.how.idmap_how_u.nldap.dn =
1738 				    strdup(values[7]);
1739 				res->info.how.idmap_how_u.nldap.attr =
1740 				    strdup(values[8]);
1741 				res->info.how.idmap_how_u.nldap.value =
1742 				    strdup(values[9]);
1743 				break;
1744 
1745 			case IDMAP_MAP_TYPE_RULE_BASED:
1746 				res->info.how.idmap_how_u.rule.windomain =
1747 				    strdup(values[10]);
1748 				res->info.how.idmap_how_u.rule.winname =
1749 				    strdup(values[11]);
1750 				res->info.how.idmap_how_u.rule.unixname =
1751 				    strdup(values[12]);
1752 				res->info.how.idmap_how_u.rule.is_nt4 =
1753 				    strtoul(values[13], &end, 1);
1754 				res->info.how.idmap_how_u.rule.is_user =
1755 				    is_user;
1756 				res->info.how.idmap_how_u.rule.is_wuser =
1757 				    strtoul(values[5], &end, 1);
1758 				break;
1759 
1760 			case IDMAP_MAP_TYPE_EPHEMERAL:
1761 				break;
1762 
1763 			case IDMAP_MAP_TYPE_LOCAL_SID:
1764 				break;
1765 
1766 			case IDMAP_MAP_TYPE_KNOWN_SID:
1767 				break;
1768 
1769 			case IDMAP_MAP_TYPE_IDMU:
1770 				res->info.how.idmap_how_u.idmu.dn =
1771 				    strdup(values[7]);
1772 				res->info.how.idmap_how_u.idmu.attr =
1773 				    strdup(values[8]);
1774 				res->info.how.idmap_how_u.idmu.value =
1775 				    strdup(values[9]);
1776 				break;
1777 
1778 			default:
1779 				/* Unknown mapping type */
1780 				assert(FALSE);
1781 			}
1782 		}
1783 	}
1784 	if (vm != NULL)
1785 		(void) sqlite_finalize(vm, NULL);
1786 	return (retcode);
1787 }
1788 
1789 /*
1790  * Previous versions used two enumerations for representing types.
1791  * One of those has largely been eliminated, but was used in the
1792  * name cache table and so during an upgrade might still be visible.
1793  * In addition, the test suite prepopulates the cache with these values.
1794  *
1795  * This function translates those old values into the new values.
1796  *
1797  * This code deliberately does not use symbolic values for the legacy
1798  * values.  This is the *only* place where they should be used.
1799  */
1800 static
1801 idmap_id_type
xlate_legacy_type(int type)1802 xlate_legacy_type(int type)
1803 {
1804 	switch (type) {
1805 	case -1004:	/* _IDMAP_T_USER */
1806 		return (IDMAP_USID);
1807 	case -1005:	/* _IDMAP_T_GROUP */
1808 		return (IDMAP_GSID);
1809 	default:
1810 		return (type);
1811 	}
1812 	NOTE(NOTREACHED)
1813 }
1814 
1815 static
1816 idmap_retcode
lookup_cache_sid2name(sqlite * cache,const char * sidprefix,idmap_rid_t rid,char ** canonname,char ** canondomain,idmap_id_type * type)1817 lookup_cache_sid2name(sqlite *cache, const char *sidprefix, idmap_rid_t rid,
1818     char **canonname, char **canondomain, idmap_id_type *type)
1819 {
1820 	char		*end;
1821 	char		*sql = NULL;
1822 	const char	**values;
1823 	sqlite_vm	*vm = NULL;
1824 	int		ncol;
1825 	time_t		curtime;
1826 	idmap_retcode	retcode = IDMAP_SUCCESS;
1827 
1828 	/* Get current time */
1829 	errno = 0;
1830 	if ((curtime = time(NULL)) == (time_t)-1) {
1831 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
1832 		    strerror(errno));
1833 		retcode = IDMAP_ERR_INTERNAL;
1834 		goto out;
1835 	}
1836 
1837 	/* SQL to lookup the cache */
1838 	sql = sqlite_mprintf("SELECT canon_name, domain, type "
1839 	    "FROM name_cache WHERE "
1840 	    "sidprefix = %Q AND rid = %u AND "
1841 	    "(expiration = 0 OR expiration ISNULL OR "
1842 	    "expiration > %d);",
1843 	    sidprefix, rid, curtime);
1844 	if (sql == NULL) {
1845 		idmapdlog(LOG_ERR, "Out of memory");
1846 		retcode = IDMAP_ERR_MEMORY;
1847 		goto out;
1848 	}
1849 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 3, &values);
1850 	sqlite_freemem(sql);
1851 
1852 	if (retcode == IDMAP_SUCCESS) {
1853 		if (type != NULL) {
1854 			if (values[2] == NULL) {
1855 				retcode = IDMAP_ERR_CACHE;
1856 				goto out;
1857 			}
1858 			*type = xlate_legacy_type(strtol(values[2], &end, 10));
1859 		}
1860 
1861 		if (canonname != NULL && values[0] != NULL) {
1862 			if ((*canonname = strdup(values[0])) == NULL) {
1863 				idmapdlog(LOG_ERR, "Out of memory");
1864 				retcode = IDMAP_ERR_MEMORY;
1865 				goto out;
1866 			}
1867 		}
1868 
1869 		if (canondomain != NULL && values[1] != NULL) {
1870 			if ((*canondomain = strdup(values[1])) == NULL) {
1871 				if (canonname != NULL) {
1872 					free(*canonname);
1873 					*canonname = NULL;
1874 				}
1875 				idmapdlog(LOG_ERR, "Out of memory");
1876 				retcode = IDMAP_ERR_MEMORY;
1877 				goto out;
1878 			}
1879 		}
1880 	}
1881 
1882 out:
1883 	if (vm != NULL)
1884 		(void) sqlite_finalize(vm, NULL);
1885 	return (retcode);
1886 }
1887 
1888 /*
1889  * Given SID, find winname using name_cache OR
1890  * Given winname, find SID using name_cache.
1891  * Used when mapping win to unix i.e. req->id1 is windows id and
1892  * req->id2 is unix id
1893  */
1894 static
1895 idmap_retcode
lookup_name_cache(sqlite * cache,idmap_mapping * req,idmap_id_res * res)1896 lookup_name_cache(sqlite *cache, idmap_mapping *req, idmap_id_res *res)
1897 {
1898 	idmap_id_type	type = -1;
1899 	idmap_retcode	retcode;
1900 	char		*sidprefix = NULL;
1901 	idmap_rid_t	rid;
1902 	char		*name = NULL, *domain = NULL;
1903 
1904 	/* Done if we've both sid and winname */
1905 	if (req->id1.idmap_id_u.sid.prefix != NULL && req->id1name != NULL) {
1906 		/* Don't bother TRACE()ing, too boring */
1907 		return (IDMAP_SUCCESS);
1908 	}
1909 
1910 	if (req->id1.idmap_id_u.sid.prefix != NULL) {
1911 		/* Lookup sid to winname */
1912 		retcode = lookup_cache_sid2name(cache,
1913 		    req->id1.idmap_id_u.sid.prefix,
1914 		    req->id1.idmap_id_u.sid.rid, &name, &domain, &type);
1915 	} else {
1916 		/* Lookup winame to sid */
1917 		retcode = lookup_cache_name2sid(cache, req->id1name,
1918 		    req->id1domain, &name, &sidprefix, &rid, &type);
1919 	}
1920 
1921 	if (retcode != IDMAP_SUCCESS) {
1922 		if (retcode == IDMAP_ERR_NOTFOUND) {
1923 			TRACE(req, res, "Not found in name cache");
1924 		} else {
1925 			TRACE(req, res, "Name cache lookup error=%d", retcode);
1926 		}
1927 		free(name);
1928 		free(domain);
1929 		free(sidprefix);
1930 		return (retcode);
1931 	}
1932 
1933 	req->id1.idtype = type;
1934 
1935 	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
1936 
1937 	/*
1938 	 * If we found canonical names or domain, use them instead of
1939 	 * the existing values.
1940 	 */
1941 	if (name != NULL) {
1942 		free(req->id1name);
1943 		req->id1name = name;
1944 	}
1945 	if (domain != NULL) {
1946 		free(req->id1domain);
1947 		req->id1domain = domain;
1948 	}
1949 
1950 	if (req->id1.idmap_id_u.sid.prefix == NULL) {
1951 		req->id1.idmap_id_u.sid.prefix = sidprefix;
1952 		req->id1.idmap_id_u.sid.rid = rid;
1953 	}
1954 
1955 	TRACE(req, res, "Found in name cache");
1956 	return (retcode);
1957 }
1958 
1959 
1960 
1961 static int
ad_lookup_batch_int(lookup_state_t * state,idmap_mapping_batch * batch,idmap_ids_res * result,adutils_ad_t * dir,int how_local,int * num_processed)1962 ad_lookup_batch_int(lookup_state_t *state, idmap_mapping_batch *batch,
1963     idmap_ids_res *result, adutils_ad_t *dir, int how_local,
1964     int *num_processed)
1965 {
1966 	idmap_retcode	retcode;
1967 	int		i,  num_queued, is_wuser, is_user;
1968 	int		next_request;
1969 	int		retries = 0, esidtype;
1970 	char		**unixname;
1971 	idmap_mapping	*req;
1972 	idmap_id_res	*res;
1973 	idmap_query_state_t	*qs = NULL;
1974 	idmap_how	*how;
1975 	char		**dn, **attr, **value;
1976 
1977 	*num_processed = 0;
1978 
1979 	/*
1980 	 * Since req->id2.idtype is unused, we will use it here
1981 	 * to retrieve the value of sid_type. But it needs to be
1982 	 * reset to IDMAP_NONE before we return to prevent xdr
1983 	 * from mis-interpreting req->id2 when it tries to free
1984 	 * the input argument. Other option is to allocate an
1985 	 * array of integers and use it instead for the batched
1986 	 * call. But why un-necessarily allocate memory. That may
1987 	 * be an option if req->id2.idtype cannot be re-used in
1988 	 * future.
1989 	 *
1990 	 * Similarly, we use req->id2.idmap_id_u.uid to return
1991 	 * uidNumber or gidNumber supplied by IDMU, and reset it
1992 	 * back to IDMAP_SENTINEL_PID when we're done.  Note that
1993 	 * the query always puts the result in req->id2.idmap_id_u.uid,
1994 	 * not .gid.
1995 	 */
1996 retry:
1997 	retcode = idmap_lookup_batch_start(dir, state->ad_nqueries,
1998 	    state->directory_based_mapping,
1999 	    state->defdom,
2000 	    &qs);
2001 	if (retcode != IDMAP_SUCCESS) {
2002 		if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR &&
2003 		    retries++ < ADUTILS_DEF_NUM_RETRIES)
2004 			goto retry;
2005 		degrade_svc(1, "failed to create batch for AD lookup");
2006 			goto out;
2007 	}
2008 	num_queued = 0;
2009 
2010 	restore_svc();
2011 
2012 	if (how_local & FOREST_IS_LOCAL) {
2013 		/*
2014 		 * Directory based name mapping is only performed within the
2015 		 * joined forest.  We don't trust other "trusted"
2016 		 * forests to provide DS-based name mapping information because
2017 		 * AD's definition of "cross-forest trust" does not encompass
2018 		 * this sort of behavior.
2019 		 */
2020 		idmap_lookup_batch_set_unixattr(qs,
2021 		    state->ad_unixuser_attr, state->ad_unixgroup_attr);
2022 	}
2023 
2024 	for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
2025 		req = &batch->idmap_mapping_batch_val[i];
2026 		res = &result->ids.ids_val[i];
2027 		how = &res->info.how;
2028 
2029 		retcode = IDMAP_SUCCESS;
2030 		req->id2.idtype = IDMAP_NONE;
2031 		req->id2.idmap_id_u.uid = IDMAP_SENTINEL_PID;
2032 
2033 		/* Skip if no AD lookup required */
2034 		if (!(req->direction & _IDMAP_F_LOOKUP_AD))
2035 			continue;
2036 
2037 		/* Skip if we've already tried and gotten a "not found" */
2038 		if (req->direction & _IDMAP_F_LOOKUP_OTHER_AD)
2039 			continue;
2040 
2041 		/* Skip if we've already either succeeded or failed */
2042 		if (res->retcode != IDMAP_ERR_RETRIABLE_NET_ERR)
2043 			continue;
2044 
2045 		if (IS_ID_SID(req->id1)) {
2046 
2047 			/* win2unix request: */
2048 
2049 			posix_id_t *pid = NULL;
2050 			unixname = dn = attr = value = NULL;
2051 			esidtype = IDMAP_SID;
2052 			if (state->directory_based_mapping ==
2053 			    DIRECTORY_MAPPING_NAME &&
2054 			    req->id2name == NULL) {
2055 				if (res->id.idtype == IDMAP_UID &&
2056 				    AD_OR_MIXED(state->nm_siduid)) {
2057 					esidtype = IDMAP_USID;
2058 					unixname = &req->id2name;
2059 				} else if (res->id.idtype == IDMAP_GID &&
2060 				    AD_OR_MIXED(state->nm_sidgid)) {
2061 					esidtype = IDMAP_GSID;
2062 					unixname = &req->id2name;
2063 				} else if (AD_OR_MIXED(state->nm_siduid) ||
2064 				    AD_OR_MIXED(state->nm_sidgid)) {
2065 					unixname = &req->id2name;
2066 				}
2067 
2068 				if (unixname != NULL) {
2069 					/*
2070 					 * Get how info for DS-based name
2071 					 * mapping only if AD or MIXED
2072 					 * mode is enabled.
2073 					 */
2074 					idmap_how_clear(&res->info.how);
2075 					res->info.src = IDMAP_MAP_SRC_NEW;
2076 					how->map_type = IDMAP_MAP_TYPE_DS_AD;
2077 					dn = &how->idmap_how_u.ad.dn;
2078 					attr = &how->idmap_how_u.ad.attr;
2079 					value = &how->idmap_how_u.ad.value;
2080 				}
2081 			} else if (state->directory_based_mapping ==
2082 			    DIRECTORY_MAPPING_IDMU &&
2083 			    (how_local & DOMAIN_IS_LOCAL)) {
2084 				/*
2085 				 * Ensure that we only do IDMU processing
2086 				 * when querying the domain we've joined.
2087 				 */
2088 				pid = &req->id2.idmap_id_u.uid;
2089 				/*
2090 				 * Get how info for IDMU based mapping.
2091 				 */
2092 				idmap_how_clear(&res->info.how);
2093 				res->info.src = IDMAP_MAP_SRC_NEW;
2094 				how->map_type = IDMAP_MAP_TYPE_IDMU;
2095 				dn = &how->idmap_how_u.idmu.dn;
2096 				attr = &how->idmap_how_u.idmu.attr;
2097 				value = &how->idmap_how_u.idmu.value;
2098 			}
2099 
2100 			if (req->id1.idmap_id_u.sid.prefix != NULL) {
2101 				/* Lookup AD by SID */
2102 				retcode = idmap_sid2name_batch_add1(
2103 				    qs, req->id1.idmap_id_u.sid.prefix,
2104 				    &req->id1.idmap_id_u.sid.rid, esidtype,
2105 				    dn, attr, value,
2106 				    (req->id1name == NULL) ?
2107 				    &req->id1name : NULL,
2108 				    (req->id1domain == NULL) ?
2109 				    &req->id1domain : NULL,
2110 				    &req->id2.idtype, unixname,
2111 				    pid,
2112 				    &res->retcode);
2113 				if (retcode == IDMAP_SUCCESS)
2114 					num_queued++;
2115 			} else {
2116 				/* Lookup AD by winname */
2117 				assert(req->id1name != NULL);
2118 				retcode = idmap_name2sid_batch_add1(
2119 				    qs, req->id1name, req->id1domain,
2120 				    esidtype,
2121 				    dn, attr, value,
2122 				    &req->id1name,
2123 				    &req->id1.idmap_id_u.sid.prefix,
2124 				    &req->id1.idmap_id_u.sid.rid,
2125 				    &req->id2.idtype, unixname,
2126 				    pid,
2127 				    &res->retcode);
2128 				if (retcode == IDMAP_SUCCESS)
2129 					num_queued++;
2130 			}
2131 
2132 		} else if (IS_ID_UID(req->id1) || IS_ID_GID(req->id1)) {
2133 
2134 			/* unix2win request: */
2135 
2136 			if (res->id.idmap_id_u.sid.prefix != NULL &&
2137 			    req->id2name != NULL) {
2138 				/* Already have SID and winname. done */
2139 				res->retcode = IDMAP_SUCCESS;
2140 				continue;
2141 			}
2142 
2143 			if (res->id.idmap_id_u.sid.prefix != NULL) {
2144 				/*
2145 				 * SID but no winname -- lookup AD by
2146 				 * SID to get winname.
2147 				 * how info is not needed here because
2148 				 * we are not retrieving unixname from
2149 				 * AD.
2150 				 */
2151 
2152 				retcode = idmap_sid2name_batch_add1(
2153 				    qs, res->id.idmap_id_u.sid.prefix,
2154 				    &res->id.idmap_id_u.sid.rid,
2155 				    IDMAP_POSIXID,
2156 				    NULL, NULL, NULL,
2157 				    &req->id2name,
2158 				    &req->id2domain, &req->id2.idtype,
2159 				    NULL, NULL, &res->retcode);
2160 				if (retcode == IDMAP_SUCCESS)
2161 					num_queued++;
2162 			} else if (req->id2name != NULL) {
2163 				/*
2164 				 * winname but no SID -- lookup AD by
2165 				 * winname to get SID.
2166 				 * how info is not needed here because
2167 				 * we are not retrieving unixname from
2168 				 * AD.
2169 				 */
2170 				retcode = idmap_name2sid_batch_add1(
2171 				    qs, req->id2name, req->id2domain,
2172 				    IDMAP_POSIXID,
2173 				    NULL, NULL, NULL, NULL,
2174 				    &res->id.idmap_id_u.sid.prefix,
2175 				    &res->id.idmap_id_u.sid.rid,
2176 				    &req->id2.idtype, NULL,
2177 				    NULL,
2178 				    &res->retcode);
2179 				if (retcode == IDMAP_SUCCESS)
2180 					num_queued++;
2181 			} else if (state->directory_based_mapping ==
2182 			    DIRECTORY_MAPPING_IDMU &&
2183 			    (how_local & DOMAIN_IS_LOCAL)) {
2184 				assert(req->id1.idmap_id_u.uid !=
2185 				    IDMAP_SENTINEL_PID);
2186 				is_user = IS_ID_UID(req->id1);
2187 				if (res->id.idtype == IDMAP_USID)
2188 					is_wuser = 1;
2189 				else if (res->id.idtype == IDMAP_GSID)
2190 					is_wuser = 0;
2191 				else
2192 					is_wuser = is_user;
2193 
2194 				/* IDMU can't do diagonal mappings */
2195 				if (is_user != is_wuser)
2196 					continue;
2197 
2198 				idmap_how_clear(&res->info.how);
2199 				res->info.src = IDMAP_MAP_SRC_NEW;
2200 				how->map_type = IDMAP_MAP_TYPE_IDMU;
2201 				retcode = idmap_pid2sid_batch_add1(
2202 				    qs, req->id1.idmap_id_u.uid, is_user,
2203 				    &how->idmap_how_u.ad.dn,
2204 				    &how->idmap_how_u.ad.attr,
2205 				    &how->idmap_how_u.ad.value,
2206 				    &res->id.idmap_id_u.sid.prefix,
2207 				    &res->id.idmap_id_u.sid.rid,
2208 				    &req->id2name, &req->id2domain,
2209 				    &req->id2.idtype, &res->retcode);
2210 				if (retcode == IDMAP_SUCCESS)
2211 					num_queued++;
2212 			} else if (req->id1name != NULL) {
2213 				/*
2214 				 * No SID and no winname but we've unixname.
2215 				 * Lookup AD by unixname to get SID.
2216 				 */
2217 				is_user = (IS_ID_UID(req->id1)) ? 1 : 0;
2218 				if (res->id.idtype == IDMAP_USID)
2219 					is_wuser = 1;
2220 				else if (res->id.idtype == IDMAP_GSID)
2221 					is_wuser = 0;
2222 				else
2223 					is_wuser = is_user;
2224 
2225 				idmap_how_clear(&res->info.how);
2226 				res->info.src = IDMAP_MAP_SRC_NEW;
2227 				how->map_type = IDMAP_MAP_TYPE_DS_AD;
2228 				retcode = idmap_unixname2sid_batch_add1(
2229 				    qs, req->id1name, is_user, is_wuser,
2230 				    &how->idmap_how_u.ad.dn,
2231 				    &how->idmap_how_u.ad.attr,
2232 				    &how->idmap_how_u.ad.value,
2233 				    &res->id.idmap_id_u.sid.prefix,
2234 				    &res->id.idmap_id_u.sid.rid,
2235 				    &req->id2name, &req->id2domain,
2236 				    &req->id2.idtype, &res->retcode);
2237 				if (retcode == IDMAP_SUCCESS)
2238 					num_queued++;
2239 			}
2240 		}
2241 
2242 		if (retcode == IDMAP_ERR_DOMAIN_NOTFOUND) {
2243 			req->direction |= _IDMAP_F_LOOKUP_OTHER_AD;
2244 			retcode = IDMAP_SUCCESS;
2245 		} else if (retcode != IDMAP_SUCCESS) {
2246 			break;
2247 		}
2248 	} /* End of for loop */
2249 
2250 	if (retcode == IDMAP_SUCCESS) {
2251 		/* add keeps track if we added an entry to the batch */
2252 		if (num_queued > 0)
2253 			retcode = idmap_lookup_batch_end(&qs);
2254 		else
2255 			idmap_lookup_release_batch(&qs);
2256 	} else {
2257 		idmap_lookup_release_batch(&qs);
2258 		num_queued = 0;
2259 		next_request = i + 1;
2260 	}
2261 
2262 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR &&
2263 	    retries++ < ADUTILS_DEF_NUM_RETRIES)
2264 		goto retry;
2265 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
2266 		degrade_svc(1, "some AD lookups timed out repeatedly");
2267 
2268 	if (retcode != IDMAP_SUCCESS) {
2269 		/* Mark any unproccessed requests for an other AD */
2270 		for (i = next_request; i < batch->idmap_mapping_batch_len;
2271 		    i++) {
2272 			req = &batch->idmap_mapping_batch_val[i];
2273 			req->direction |= _IDMAP_F_LOOKUP_OTHER_AD;
2274 
2275 		}
2276 	}
2277 
2278 	if (retcode != IDMAP_SUCCESS)
2279 		idmapdlog(LOG_NOTICE, "Failed to batch AD lookup requests");
2280 
2281 out:
2282 	/*
2283 	 * This loop does the following:
2284 	 * 1. Reset _IDMAP_F_LOOKUP_AD flag from the request.
2285 	 * 2. Reset req->id2.idtype to IDMAP_NONE
2286 	 * 3. If batch_start or batch_add failed then set the status
2287 	 *    of each request marked for AD lookup to that error.
2288 	 * 4. Evaluate the type of the AD object (i.e. user or group)
2289 	 *    and update the idtype in request.
2290 	 */
2291 	for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
2292 		idmap_id_type type;
2293 		uid_t posix_id;
2294 
2295 		req = &batch->idmap_mapping_batch_val[i];
2296 		type = req->id2.idtype;
2297 		req->id2.idtype = IDMAP_NONE;
2298 		posix_id = req->id2.idmap_id_u.uid;
2299 		req->id2.idmap_id_u.uid = IDMAP_SENTINEL_PID;
2300 		res = &result->ids.ids_val[i];
2301 
2302 		/*
2303 		 * If it didn't need AD lookup, ignore it.
2304 		 */
2305 		if (!(req->direction & _IDMAP_F_LOOKUP_AD))
2306 			continue;
2307 
2308 		/*
2309 		 * If we deferred it this time, reset for the next
2310 		 * AD server.
2311 		 */
2312 		if (req->direction & _IDMAP_F_LOOKUP_OTHER_AD) {
2313 			req->direction &= ~_IDMAP_F_LOOKUP_OTHER_AD;
2314 			continue;
2315 		}
2316 
2317 		/* Count number processed */
2318 		(*num_processed)++;
2319 
2320 		/* Reset AD lookup flag */
2321 		req->direction &= ~(_IDMAP_F_LOOKUP_AD);
2322 
2323 		/*
2324 		 * If batch_start or batch_add failed then set the
2325 		 * status of each request marked for AD lookup to
2326 		 * that error.
2327 		 */
2328 		if (retcode != IDMAP_SUCCESS) {
2329 			res->retcode = retcode;
2330 			continue;
2331 		}
2332 
2333 		if (res->retcode == IDMAP_ERR_NOTFOUND) {
2334 			/* Nothing found - remove the preset info */
2335 			idmap_how_clear(&res->info.how);
2336 		}
2337 
2338 		if (IS_ID_SID(req->id1)) {
2339 			if (res->retcode == IDMAP_ERR_NOTFOUND) {
2340 				TRACE(req, res, "Not found in AD");
2341 				continue;
2342 			}
2343 			if (res->retcode != IDMAP_SUCCESS) {
2344 				TRACE(req, res, "AD lookup error=%d",
2345 				    res->retcode);
2346 				continue;
2347 			}
2348 			/* Evaluate result type */
2349 			switch (type) {
2350 			case IDMAP_USID:
2351 				if (res->id.idtype == IDMAP_POSIXID)
2352 					res->id.idtype = IDMAP_UID;
2353 				/*
2354 				 * We found a user.  If we got information
2355 				 * from IDMU and we were expecting a user,
2356 				 * copy the id.
2357 				 */
2358 				if (posix_id != IDMAP_SENTINEL_PID &&
2359 				    res->id.idtype == IDMAP_UID) {
2360 					res->id.idmap_id_u.uid = posix_id;
2361 					res->direction = IDMAP_DIRECTION_BI;
2362 					res->info.how.map_type =
2363 					    IDMAP_MAP_TYPE_IDMU;
2364 					res->info.src = IDMAP_MAP_SRC_NEW;
2365 				}
2366 				req->id1.idtype = IDMAP_USID;
2367 				break;
2368 
2369 			case IDMAP_GSID:
2370 				if (res->id.idtype == IDMAP_POSIXID)
2371 					res->id.idtype = IDMAP_GID;
2372 				/*
2373 				 * We found a group.  If we got information
2374 				 * from IDMU and we were expecting a group,
2375 				 * copy the id.
2376 				 */
2377 				if (posix_id != IDMAP_SENTINEL_PID &&
2378 				    res->id.idtype == IDMAP_GID) {
2379 					res->id.idmap_id_u.gid = posix_id;
2380 					res->direction = IDMAP_DIRECTION_BI;
2381 					res->info.how.map_type =
2382 					    IDMAP_MAP_TYPE_IDMU;
2383 					res->info.src = IDMAP_MAP_SRC_NEW;
2384 				}
2385 				req->id1.idtype = IDMAP_GSID;
2386 				break;
2387 
2388 			default:
2389 				res->retcode = IDMAP_ERR_SID;
2390 				break;
2391 			}
2392 			TRACE(req, res, "Found in AD");
2393 			if (res->retcode == IDMAP_SUCCESS &&
2394 			    req->id1name != NULL &&
2395 			    (req->id2name == NULL ||
2396 			    res->id.idmap_id_u.uid == IDMAP_SENTINEL_PID) &&
2397 			    NLDAP_MODE(res->id.idtype, state)) {
2398 				req->direction |= _IDMAP_F_LOOKUP_NLDAP;
2399 				state->nldap_nqueries++;
2400 			}
2401 		} else if (IS_ID_UID(req->id1) || IS_ID_GID(req->id1)) {
2402 			if (res->retcode != IDMAP_SUCCESS) {
2403 				if ((!(IDMAP_FATAL_ERROR(res->retcode))) &&
2404 				    res->id.idmap_id_u.sid.prefix == NULL &&
2405 				    req->id2name == NULL) {
2406 					/*
2407 					 * If AD lookup by unixname or pid
2408 					 * failed with non fatal error
2409 					 * then clear the error (ie set
2410 					 * res->retcode to success).
2411 					 * This allows the next pass to
2412 					 * process other mapping
2413 					 * mechanisms for this request.
2414 					 */
2415 					if (res->retcode ==
2416 					    IDMAP_ERR_NOTFOUND) {
2417 						/* This is not an error */
2418 						res->retcode = IDMAP_SUCCESS;
2419 						TRACE(req, res,
2420 						    "Not found in AD");
2421 					} else {
2422 						TRACE(req, res,
2423 						"AD lookup error (ignored)");
2424 						res->retcode = IDMAP_SUCCESS;
2425 					}
2426 				} else {
2427 					TRACE(req, res, "AD lookup error");
2428 				}
2429 				continue;
2430 			}
2431 			/* Evaluate result type */
2432 			switch (type) {
2433 			case IDMAP_USID:
2434 			case IDMAP_GSID:
2435 				if (res->id.idtype == IDMAP_SID)
2436 					res->id.idtype = type;
2437 				break;
2438 
2439 			default:
2440 				res->retcode = IDMAP_ERR_SID;
2441 				break;
2442 			}
2443 			TRACE(req, res, "Found in AD");
2444 		}
2445 	}
2446 
2447 	return (retcode);
2448 }
2449 
2450 
2451 
2452 /*
2453  * Batch AD lookups
2454  */
2455 idmap_retcode
ad_lookup_batch(lookup_state_t * state,idmap_mapping_batch * batch,idmap_ids_res * result)2456 ad_lookup_batch(lookup_state_t *state, idmap_mapping_batch *batch,
2457     idmap_ids_res *result)
2458 {
2459 	idmap_retcode	retcode;
2460 	int		i, j;
2461 	idmap_mapping	*req;
2462 	idmap_id_res	*res;
2463 	int		num_queries;
2464 	int		num_processed;
2465 
2466 	if (state->ad_nqueries == 0)
2467 		return (IDMAP_SUCCESS);
2468 
2469 	for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
2470 		req = &batch->idmap_mapping_batch_val[i];
2471 		res = &result->ids.ids_val[i];
2472 
2473 		/* Skip if not marked for AD lookup or already in error. */
2474 		if (!(req->direction & _IDMAP_F_LOOKUP_AD) ||
2475 		    res->retcode != IDMAP_SUCCESS)
2476 			continue;
2477 
2478 		/* Init status */
2479 		res->retcode = IDMAP_ERR_RETRIABLE_NET_ERR;
2480 	}
2481 
2482 	RDLOCK_CONFIG();
2483 	num_queries = state->ad_nqueries;
2484 
2485 	if (_idmapdstate.num_gcs == 0 && _idmapdstate.num_dcs == 0) {
2486 		/* Case of no ADs */
2487 		retcode = IDMAP_ERR_NO_ACTIVEDIRECTORY;
2488 		for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
2489 			req = &batch->idmap_mapping_batch_val[i];
2490 			res = &result->ids.ids_val[i];
2491 			if (!(req->direction & _IDMAP_F_LOOKUP_AD))
2492 				continue;
2493 			req->direction &= ~(_IDMAP_F_LOOKUP_AD);
2494 			res->retcode = IDMAP_ERR_NO_ACTIVEDIRECTORY;
2495 		}
2496 		goto out;
2497 	}
2498 
2499 	if (state->directory_based_mapping == DIRECTORY_MAPPING_IDMU) {
2500 		for (i = 0; i < _idmapdstate.num_dcs && num_queries > 0; i++) {
2501 
2502 			retcode = ad_lookup_batch_int(state, batch,
2503 			    result, _idmapdstate.dcs[i],
2504 			    i == 0 ? DOMAIN_IS_LOCAL|FOREST_IS_LOCAL : 0,
2505 			    &num_processed);
2506 			num_queries -= num_processed;
2507 
2508 		}
2509 	}
2510 
2511 	for (i = 0; i < _idmapdstate.num_gcs && num_queries > 0; i++) {
2512 
2513 		retcode = ad_lookup_batch_int(state, batch, result,
2514 		    _idmapdstate.gcs[i],
2515 		    i == 0 ? FOREST_IS_LOCAL : 0,
2516 		    &num_processed);
2517 		num_queries -= num_processed;
2518 
2519 	}
2520 
2521 	/*
2522 	 * There are no more ADs to try.  Return errors for any
2523 	 * remaining requests.
2524 	 */
2525 	if (num_queries > 0) {
2526 		for (j = 0; j < batch->idmap_mapping_batch_len; j++) {
2527 			req = &batch->idmap_mapping_batch_val[j];
2528 			res = &result->ids.ids_val[j];
2529 			if (!(req->direction & _IDMAP_F_LOOKUP_AD))
2530 				continue;
2531 			req->direction &= ~(_IDMAP_F_LOOKUP_AD);
2532 			res->retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
2533 		}
2534 	}
2535 
2536 out:
2537 	UNLOCK_CONFIG();
2538 
2539 	/* AD lookups done. Reset state->ad_nqueries and return */
2540 	state->ad_nqueries = 0;
2541 	return (retcode);
2542 }
2543 
2544 /*
2545  * Convention when processing win2unix requests:
2546  *
2547  * Windows identity:
2548  * req->id1name =
2549  *              winname if given otherwise winname found will be placed
2550  *              here.
2551  * req->id1domain =
2552  *              windomain if given otherwise windomain found will be
2553  *              placed here.
2554  * req->id1.idtype =
2555  *              Either IDMAP_SID/USID/GSID. If this is IDMAP_SID then it'll
2556  *              be set to IDMAP_USID/GSID depending upon whether the
2557  *              given SID is user or group respectively. The user/group-ness
2558  *              is determined either when looking up well-known SIDs table OR
2559  *              if the SID is found in namecache OR by ad_lookup_batch().
2560  * req->id1..sid.[prefix, rid] =
2561  *              SID if given otherwise SID found will be placed here.
2562  *
2563  * Unix identity:
2564  * req->id2name =
2565  *              unixname found will be placed here.
2566  * req->id2domain =
2567  *              NOT USED
2568  * res->id.idtype =
2569  *              Target type initialized from req->id2.idtype. If
2570  *              it is IDMAP_POSIXID then actual type (IDMAP_UID/GID) found
2571  *              will be placed here.
2572  * res->id..[uid or gid] =
2573  *              UID/GID found will be placed here.
2574  *
2575  * Others:
2576  * res->retcode =
2577  *              Return status for this request will be placed here.
2578  * res->direction =
2579  *              Direction found will be placed here. Direction
2580  *              meaning whether the resultant mapping is valid
2581  *              only from win2unix or bi-directional.
2582  * req->direction =
2583  *              INTERNAL USE. Used by idmapd to set various
2584  *              flags (_IDMAP_F_xxxx) to aid in processing
2585  *              of the request.
2586  * req->id2.idtype =
2587  *              INTERNAL USE. Initially this is the requested target
2588  *              type and is used to initialize res->id.idtype.
2589  *              ad_lookup_batch() uses this field temporarily to store
2590  *              sid_type obtained by the batched AD lookups and after
2591  *              use resets it to IDMAP_NONE to prevent xdr from
2592  *              mis-interpreting the contents of req->id2.
2593  * req->id2.idmap_id_u.uid =
2594  *              INTERNAL USE.  If the AD lookup finds IDMU data
2595  *		(uidNumber or gidNumber, depending on the type of
2596  *		the entry), it's left here.
2597  */
2598 
2599 /*
2600  * This function does the following:
2601  * 1. Lookup well-known SIDs table.
2602  * 2. Check if the given SID is a local-SID and if so extract UID/GID from it.
2603  * 3. Lookup cache.
2604  * 4. Check if the client does not want new mapping to be allocated
2605  *    in which case this pass is the final pass.
2606  * 5. Set AD lookup flag if it determines that the next stage needs
2607  *    to do AD lookup.
2608  */
2609 idmap_retcode
sid2pid_first_pass(lookup_state_t * state,idmap_mapping * req,idmap_id_res * res)2610 sid2pid_first_pass(lookup_state_t *state, idmap_mapping *req,
2611     idmap_id_res *res)
2612 {
2613 	idmap_retcode	retcode;
2614 	int		wksid;
2615 
2616 	/* Initialize result */
2617 	res->id.idtype = req->id2.idtype;
2618 	res->id.idmap_id_u.uid = IDMAP_SENTINEL_PID;
2619 	res->direction = IDMAP_DIRECTION_UNDEF;
2620 	wksid = 0;
2621 
2622 	if (EMPTY_STRING(req->id1.idmap_id_u.sid.prefix)) {
2623 		/* They have to give us *something* to work with! */
2624 		if (req->id1name == NULL) {
2625 			retcode = IDMAP_ERR_ARG;
2626 			goto out;
2627 		}
2628 
2629 		/* sanitize sidprefix */
2630 		free(req->id1.idmap_id_u.sid.prefix);
2631 		req->id1.idmap_id_u.sid.prefix = NULL;
2632 
2633 		/* Allow for a fully-qualified name in the "name" parameter */
2634 		if (req->id1domain == NULL) {
2635 			char *p;
2636 			p = strchr(req->id1name, '@');
2637 			if (p != NULL) {
2638 				char *q;
2639 				q = req->id1name;
2640 				req->id1name = uu_strndup(q, p - req->id1name);
2641 				req->id1domain = strdup(p+1);
2642 				free(q);
2643 				if (req->id1name == NULL ||
2644 				    req->id1domain == NULL) {
2645 					retcode = IDMAP_ERR_MEMORY;
2646 					goto out;
2647 				}
2648 			}
2649 		}
2650 	}
2651 
2652 	/* Lookup well-known SIDs table */
2653 	retcode = lookup_wksids_sid2pid(req, res, &wksid);
2654 	if (retcode == IDMAP_SUCCESS) {
2655 		/* Found a well-known account with a hardwired mapping */
2656 		TRACE(req, res, "Hardwired mapping");
2657 		goto out;
2658 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
2659 		TRACE(req, res,
2660 		    "Well-known account lookup failed, code %d", retcode);
2661 		goto out;
2662 	}
2663 
2664 	if (wksid) {
2665 		/* Found a well-known account, but no mapping */
2666 		TRACE(req, res, "Well-known account");
2667 	} else {
2668 		TRACE(req, res, "Not a well-known account");
2669 
2670 		/* Check if this is a localsid */
2671 		retcode = lookup_localsid2pid(req, res);
2672 		if (retcode == IDMAP_SUCCESS) {
2673 			TRACE(req, res, "Local SID");
2674 			goto out;
2675 		} else if (retcode != IDMAP_ERR_NOTFOUND) {
2676 			TRACE(req, res,
2677 			    "Local SID lookup error=%d", retcode);
2678 			goto out;
2679 		}
2680 		TRACE(req, res, "Not a local SID");
2681 
2682 		if (ALLOW_WK_OR_LOCAL_SIDS_ONLY(req)) {
2683 			retcode = IDMAP_ERR_NONE_GENERATED;
2684 			goto out;
2685 		}
2686 	}
2687 
2688 	/*
2689 	 * If this is a name-based request and we don't have a domain,
2690 	 * use the default domain.  Note that the well-known identity
2691 	 * cases will have supplied a SID prefix already, and that we
2692 	 * don't (yet?) support looking up a local user through a Windows
2693 	 * style name.
2694 	 */
2695 	if (req->id1.idmap_id_u.sid.prefix == NULL &&
2696 	    req->id1name != NULL && req->id1domain == NULL) {
2697 		if (state->defdom == NULL) {
2698 			retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
2699 			goto out;
2700 		}
2701 		req->id1domain = strdup(state->defdom);
2702 		if (req->id1domain == NULL) {
2703 			retcode = IDMAP_ERR_MEMORY;
2704 			goto out;
2705 		}
2706 		TRACE(req, res, "Added default domain");
2707 	}
2708 
2709 	/* Lookup cache */
2710 	retcode = lookup_cache_sid2pid(state->cache, req, res);
2711 	if (retcode == IDMAP_SUCCESS) {
2712 		TRACE(req, res, "Found in mapping cache");
2713 		goto out;
2714 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
2715 		TRACE(req, res, "Mapping cache lookup error=%d", retcode);
2716 		goto out;
2717 	}
2718 	TRACE(req, res, "Not found in mapping cache");
2719 
2720 	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req) || AVOID_NAMESERVICE(req)) {
2721 		retcode = IDMAP_ERR_NONE_GENERATED;
2722 		goto out;
2723 	}
2724 
2725 	/*
2726 	 * Failed to find non-expired entry in cache. Next step is
2727 	 * to determine if this request needs to be batched for AD lookup.
2728 	 *
2729 	 * At this point we have either sid or winname or both. If we don't
2730 	 * have both then lookup name_cache for the sid or winname
2731 	 * whichever is missing. If not found then this request will be
2732 	 * batched for AD lookup.
2733 	 */
2734 	retcode = lookup_name_cache(state->cache, req, res);
2735 	if (retcode == IDMAP_SUCCESS) {
2736 		if (res->id.idtype == IDMAP_POSIXID) {
2737 			if (req->id1.idtype == IDMAP_USID)
2738 				res->id.idtype = IDMAP_UID;
2739 			else
2740 				res->id.idtype = IDMAP_GID;
2741 		}
2742 	} else if (retcode != IDMAP_ERR_NOTFOUND)
2743 		goto out;
2744 
2745 	if (_idmapdstate.cfg->pgcfg.use_lsa &&
2746 	    _idmapdstate.cfg->pgcfg.domain_name != NULL) {
2747 		/*
2748 		 * If we don't have both name and SID, try looking up the
2749 		 * entry with LSA.
2750 		 */
2751 		if (req->id1.idmap_id_u.sid.prefix != NULL &&
2752 		    req->id1name == NULL) {
2753 
2754 			retcode = lookup_lsa_by_sid(
2755 			    req->id1.idmap_id_u.sid.prefix,
2756 			    req->id1.idmap_id_u.sid.rid,
2757 			    &req->id1name, &req->id1domain, &req->id1.idtype);
2758 			if (retcode == IDMAP_SUCCESS) {
2759 				TRACE(req, res, "Found with LSA");
2760 			} else if (retcode == IDMAP_ERR_NOTFOUND) {
2761 				TRACE(req, res, "Not found with LSA");
2762 			} else {
2763 				TRACE(req, res, "LSA error %d", retcode);
2764 				goto out;
2765 			}
2766 
2767 		} else  if (req->id1name != NULL &&
2768 		    req->id1.idmap_id_u.sid.prefix == NULL) {
2769 			char *canonname;
2770 			char *canondomain;
2771 
2772 			retcode = lookup_lsa_by_name(
2773 			    req->id1name, req->id1domain,
2774 			    &req->id1.idmap_id_u.sid.prefix,
2775 			    &req->id1.idmap_id_u.sid.rid,
2776 			    &canonname, &canondomain,
2777 			    &req->id1.idtype);
2778 			if (retcode == IDMAP_SUCCESS) {
2779 				free(req->id1name);
2780 				req->id1name = canonname;
2781 				free(req->id1domain);
2782 				req->id1domain = canondomain;
2783 				TRACE(req, res, "Found with LSA");
2784 			} else if (retcode == IDMAP_ERR_NOTFOUND) {
2785 				TRACE(req, res, "Not found with LSA");
2786 			} else {
2787 				TRACE(req, res, "LSA error %d", retcode);
2788 				goto out;
2789 			}
2790 		}
2791 	}
2792 
2793 	/*
2794 	 * Set the flag to indicate that we are not done yet so that
2795 	 * subsequent passes considers this request for name-based
2796 	 * mapping and ephemeral mapping.
2797 	 */
2798 	state->sid2pid_done = FALSE;
2799 	req->direction |= _IDMAP_F_NOTDONE;
2800 
2801 	/*
2802 	 * Even if we have both sid and winname, we still may need to batch
2803 	 * this request for AD lookup if we don't have unixname and
2804 	 * directory-based name mapping (AD or mixed) is enabled.
2805 	 * We avoid AD lookup for well-known SIDs because they don't have
2806 	 * regular AD objects.
2807 	 */
2808 	if (retcode != IDMAP_SUCCESS ||
2809 	    (!wksid && req->id2name == NULL &&
2810 	    AD_OR_MIXED_MODE(res->id.idtype, state)) ||
2811 	    (!wksid && res->id.idmap_id_u.uid == IDMAP_SENTINEL_PID &&
2812 	    state->directory_based_mapping == DIRECTORY_MAPPING_IDMU)) {
2813 		retcode = IDMAP_SUCCESS;
2814 		req->direction |= _IDMAP_F_LOOKUP_AD;
2815 		state->ad_nqueries++;
2816 	} else if (NLDAP_MODE(res->id.idtype, state)) {
2817 		req->direction |= _IDMAP_F_LOOKUP_NLDAP;
2818 		state->nldap_nqueries++;
2819 	}
2820 
2821 
2822 out:
2823 	res->retcode = idmap_stat4prot(retcode);
2824 	/*
2825 	 * If we are done and there was an error then set fallback pid
2826 	 * in the result.
2827 	 */
2828 	if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS)
2829 		res->id.idmap_id_u.uid = UID_NOBODY;
2830 	return (retcode);
2831 }
2832 
2833 /*
2834  * Generate SID using the following convention
2835  *	<machine-sid-prefix>-<1000 + uid>
2836  *	<machine-sid-prefix>-<2^31 + gid>
2837  */
2838 static
2839 idmap_retcode
generate_localsid(idmap_mapping * req,idmap_id_res * res,int is_user,int fallback)2840 generate_localsid(idmap_mapping *req, idmap_id_res *res, int is_user,
2841     int fallback)
2842 {
2843 	free(res->id.idmap_id_u.sid.prefix);
2844 	res->id.idmap_id_u.sid.prefix = NULL;
2845 
2846 	/*
2847 	 * Diagonal mapping for localSIDs not supported because of the
2848 	 * way we generate localSIDs.
2849 	 */
2850 	if (is_user && res->id.idtype == IDMAP_GSID)
2851 		return (IDMAP_ERR_NOTGROUP);
2852 	if (!is_user && res->id.idtype == IDMAP_USID)
2853 		return (IDMAP_ERR_NOTUSER);
2854 
2855 	/* Skip 1000 UIDs */
2856 	if (is_user &&
2857 	    req->id1.idmap_id_u.uid + LOCALRID_UID_MIN > LOCALRID_UID_MAX)
2858 		return (IDMAP_ERR_NOMAPPING);
2859 
2860 	RDLOCK_CONFIG();
2861 	/*
2862 	 * machine_sid is never NULL because if it is we won't be here.
2863 	 * No need to assert because strdup(NULL) will core anyways.
2864 	 */
2865 	res->id.idmap_id_u.sid.prefix =
2866 	    strdup(_idmapdstate.cfg->pgcfg.machine_sid);
2867 	if (res->id.idmap_id_u.sid.prefix == NULL) {
2868 		UNLOCK_CONFIG();
2869 		idmapdlog(LOG_ERR, "Out of memory");
2870 		return (IDMAP_ERR_MEMORY);
2871 	}
2872 	UNLOCK_CONFIG();
2873 	res->id.idmap_id_u.sid.rid =
2874 	    (is_user) ? req->id1.idmap_id_u.uid + LOCALRID_UID_MIN :
2875 	    req->id1.idmap_id_u.gid + LOCALRID_GID_MIN;
2876 	res->direction = IDMAP_DIRECTION_BI;
2877 	if (res->id.idtype == IDMAP_SID)
2878 		res->id.idtype = is_user ? IDMAP_USID : IDMAP_GSID;
2879 
2880 	if (!fallback) {
2881 		res->info.how.map_type = IDMAP_MAP_TYPE_LOCAL_SID;
2882 		res->info.src = IDMAP_MAP_SRC_ALGORITHMIC;
2883 	}
2884 
2885 	/*
2886 	 * Don't update name_cache because local sids don't have
2887 	 * valid windows names.
2888 	 */
2889 	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
2890 	return (IDMAP_SUCCESS);
2891 }
2892 
2893 static
2894 idmap_retcode
lookup_localsid2pid(idmap_mapping * req,idmap_id_res * res)2895 lookup_localsid2pid(idmap_mapping *req, idmap_id_res *res)
2896 {
2897 	char		*sidprefix;
2898 	uint32_t	rid;
2899 	int		s;
2900 
2901 	/*
2902 	 * If the sidprefix == localsid then UID = last RID - 1000 or
2903 	 * GID = last RID - 2^31.
2904 	 */
2905 	if ((sidprefix = req->id1.idmap_id_u.sid.prefix) == NULL)
2906 		/* This means we are looking up by winname */
2907 		return (IDMAP_ERR_NOTFOUND);
2908 	rid = req->id1.idmap_id_u.sid.rid;
2909 
2910 	RDLOCK_CONFIG();
2911 	s = (_idmapdstate.cfg->pgcfg.machine_sid) ?
2912 	    strcasecmp(sidprefix, _idmapdstate.cfg->pgcfg.machine_sid) : 1;
2913 	UNLOCK_CONFIG();
2914 
2915 	/*
2916 	 * If the given sidprefix does not match machine_sid then this is
2917 	 * not a local SID.
2918 	 */
2919 	if (s != 0)
2920 		return (IDMAP_ERR_NOTFOUND);
2921 
2922 	switch (res->id.idtype) {
2923 	case IDMAP_UID:
2924 		if (rid < LOCALRID_UID_MIN || rid > LOCALRID_UID_MAX)
2925 			return (IDMAP_ERR_ARG);
2926 		res->id.idmap_id_u.uid = rid - LOCALRID_UID_MIN;
2927 		break;
2928 	case IDMAP_GID:
2929 		if (rid < LOCALRID_GID_MIN)
2930 			return (IDMAP_ERR_ARG);
2931 		res->id.idmap_id_u.gid = rid - LOCALRID_GID_MIN;
2932 		break;
2933 	case IDMAP_POSIXID:
2934 		if (rid >= LOCALRID_GID_MIN) {
2935 			res->id.idmap_id_u.gid = rid - LOCALRID_GID_MIN;
2936 			res->id.idtype = IDMAP_GID;
2937 		} else if (rid >= LOCALRID_UID_MIN) {
2938 			res->id.idmap_id_u.uid = rid - LOCALRID_UID_MIN;
2939 			res->id.idtype = IDMAP_UID;
2940 		} else {
2941 			return (IDMAP_ERR_ARG);
2942 		}
2943 		break;
2944 	default:
2945 		return (IDMAP_ERR_NOTSUPPORTED);
2946 	}
2947 	res->info.how.map_type = IDMAP_MAP_TYPE_LOCAL_SID;
2948 	res->info.src = IDMAP_MAP_SRC_ALGORITHMIC;
2949 	return (IDMAP_SUCCESS);
2950 }
2951 
2952 /*
2953  * Name service lookup by unixname to get pid
2954  */
2955 static
2956 idmap_retcode
ns_lookup_byname(const char * name,const char * lower_name,idmap_id * id)2957 ns_lookup_byname(const char *name, const char *lower_name, idmap_id *id)
2958 {
2959 	struct passwd	pwd, *pwdp;
2960 	struct group	grp, *grpp;
2961 	char		*buf;
2962 	static size_t	pwdbufsiz = 0;
2963 	static size_t	grpbufsiz = 0;
2964 
2965 	switch (id->idtype) {
2966 	case IDMAP_UID:
2967 		if (pwdbufsiz == 0)
2968 			pwdbufsiz = sysconf(_SC_GETPW_R_SIZE_MAX);
2969 		buf = alloca(pwdbufsiz);
2970 		pwdp = getpwnam_r(name, &pwd, buf, pwdbufsiz);
2971 		if (pwdp == NULL && errno == 0 && lower_name != NULL &&
2972 		    name != lower_name && strcmp(name, lower_name) != 0)
2973 			pwdp = getpwnam_r(lower_name, &pwd, buf, pwdbufsiz);
2974 		if (pwdp == NULL) {
2975 			if (errno == 0)
2976 				return (IDMAP_ERR_NOTFOUND);
2977 			else
2978 				return (IDMAP_ERR_INTERNAL);
2979 		}
2980 		id->idmap_id_u.uid = pwd.pw_uid;
2981 		break;
2982 	case IDMAP_GID:
2983 		if (grpbufsiz == 0)
2984 			grpbufsiz = sysconf(_SC_GETGR_R_SIZE_MAX);
2985 		buf = alloca(grpbufsiz);
2986 		grpp = getgrnam_r(name, &grp, buf, grpbufsiz);
2987 		if (grpp == NULL && errno == 0 && lower_name != NULL &&
2988 		    name != lower_name && strcmp(name, lower_name) != 0)
2989 			grpp = getgrnam_r(lower_name, &grp, buf, grpbufsiz);
2990 		if (grpp == NULL) {
2991 			if (errno == 0)
2992 				return (IDMAP_ERR_NOTFOUND);
2993 			else
2994 				return (IDMAP_ERR_INTERNAL);
2995 		}
2996 		id->idmap_id_u.gid = grp.gr_gid;
2997 		break;
2998 	default:
2999 		return (IDMAP_ERR_ARG);
3000 	}
3001 	return (IDMAP_SUCCESS);
3002 }
3003 
3004 
3005 /*
3006  * Name service lookup by pid to get unixname
3007  */
3008 static
3009 idmap_retcode
ns_lookup_bypid(uid_t pid,int is_user,char ** unixname)3010 ns_lookup_bypid(uid_t pid, int is_user, char **unixname)
3011 {
3012 	struct passwd	pwd;
3013 	struct group	grp;
3014 	char		*buf;
3015 	static size_t	pwdbufsiz = 0;
3016 	static size_t	grpbufsiz = 0;
3017 
3018 	if (is_user) {
3019 		if (pwdbufsiz == 0)
3020 			pwdbufsiz = sysconf(_SC_GETPW_R_SIZE_MAX);
3021 		buf = alloca(pwdbufsiz);
3022 		errno = 0;
3023 		if (getpwuid_r(pid, &pwd, buf, pwdbufsiz) == NULL) {
3024 			if (errno == 0)
3025 				return (IDMAP_ERR_NOTFOUND);
3026 			else
3027 				return (IDMAP_ERR_INTERNAL);
3028 		}
3029 		*unixname = strdup(pwd.pw_name);
3030 	} else {
3031 		if (grpbufsiz == 0)
3032 			grpbufsiz = sysconf(_SC_GETGR_R_SIZE_MAX);
3033 		buf = alloca(grpbufsiz);
3034 		errno = 0;
3035 		if (getgrgid_r(pid, &grp, buf, grpbufsiz) == NULL) {
3036 			if (errno == 0)
3037 				return (IDMAP_ERR_NOTFOUND);
3038 			else
3039 				return (IDMAP_ERR_INTERNAL);
3040 		}
3041 		*unixname = strdup(grp.gr_name);
3042 	}
3043 	if (*unixname == NULL)
3044 		return (IDMAP_ERR_MEMORY);
3045 	return (IDMAP_SUCCESS);
3046 }
3047 
3048 /*
3049  * Name-based mapping
3050  *
3051  * Case 1: If no rule matches do ephemeral
3052  *
3053  * Case 2: If rule matches and unixname is "" then return no mapping.
3054  *
3055  * Case 3: If rule matches and unixname is specified then lookup name
3056  *  service using the unixname. If unixname not found then return no mapping.
3057  *
3058  * Case 4: If rule matches and unixname is * then lookup name service
3059  *  using winname as the unixname. If unixname not found then process
3060  *  other rules using the lookup order. If no other rule matches then do
3061  *  ephemeral. Otherwise, based on the matched rule do Case 2 or 3 or 4.
3062  *  This allows us to specify a fallback unixname per _domain_ or no mapping
3063  *  instead of the default behaviour of doing ephemeral mapping.
3064  *
3065  * Example 1:
3066  * *@sfbay == *
3067  * If looking up windows users foo@sfbay and foo does not exists in
3068  * the name service then foo@sfbay will be mapped to an ephemeral id.
3069  *
3070  * Example 2:
3071  * *@sfbay == *
3072  * *@sfbay => guest
3073  * If looking up windows users foo@sfbay and foo does not exists in
3074  * the name service then foo@sfbay will be mapped to guest.
3075  *
3076  * Example 3:
3077  * *@sfbay == *
3078  * *@sfbay => ""
3079  * If looking up windows users foo@sfbay and foo does not exists in
3080  * the name service then we will return no mapping for foo@sfbay.
3081  *
3082  */
3083 static
3084 idmap_retcode
name_based_mapping_sid2pid(lookup_state_t * state,idmap_mapping * req,idmap_id_res * res)3085 name_based_mapping_sid2pid(lookup_state_t *state,
3086     idmap_mapping *req, idmap_id_res *res)
3087 {
3088 	const char	*unixname, *windomain;
3089 	char		*sql = NULL, *errmsg = NULL, *lower_winname = NULL;
3090 	idmap_retcode	retcode;
3091 	char		*end, *lower_unixname, *winname;
3092 	const char	**values;
3093 	sqlite_vm	*vm = NULL;
3094 	int		ncol, r, is_user, is_wuser;
3095 	idmap_namerule	*rule = &res->info.how.idmap_how_u.rule;
3096 	int		direction;
3097 	const char	*me = "name_based_mapping_sid2pid";
3098 
3099 	assert(req->id1name != NULL); /* We have winname */
3100 	assert(req->id2name == NULL); /* We don't have unixname */
3101 
3102 	winname = req->id1name;
3103 	windomain = req->id1domain;
3104 
3105 	switch (req->id1.idtype) {
3106 	case IDMAP_USID:
3107 		is_wuser = 1;
3108 		break;
3109 	case IDMAP_GSID:
3110 		is_wuser = 0;
3111 		break;
3112 	default:
3113 		idmapdlog(LOG_ERR, "%s: Unable to determine if the "
3114 		    "given Windows id is user or group.", me);
3115 		return (IDMAP_ERR_INTERNAL);
3116 	}
3117 
3118 	switch (res->id.idtype) {
3119 	case IDMAP_UID:
3120 		is_user = 1;
3121 		break;
3122 	case IDMAP_GID:
3123 		is_user = 0;
3124 		break;
3125 	case IDMAP_POSIXID:
3126 		is_user = is_wuser;
3127 		res->id.idtype = is_user ? IDMAP_UID : IDMAP_GID;
3128 		break;
3129 	}
3130 
3131 	if (windomain == NULL)
3132 		windomain = "";
3133 
3134 	if ((lower_winname = tolower_u8(winname)) == NULL)
3135 		lower_winname = winname;    /* hope for the best */
3136 	sql = sqlite_mprintf(
3137 	    "SELECT unixname, u2w_order, winname_display, windomain, is_nt4 "
3138 	    "FROM namerules WHERE "
3139 	    "w2u_order > 0 AND is_user = %d AND is_wuser = %d AND "
3140 	    "(winname = %Q OR winname = '*') AND "
3141 	    "(windomain = %Q OR windomain = '*') "
3142 	    "ORDER BY w2u_order ASC;",
3143 	    is_user, is_wuser, lower_winname, windomain);
3144 	if (sql == NULL) {
3145 		idmapdlog(LOG_ERR, "Out of memory");
3146 		retcode = IDMAP_ERR_MEMORY;
3147 		goto out;
3148 	}
3149 
3150 	if (sqlite_compile(state->db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
3151 		retcode = IDMAP_ERR_INTERNAL;
3152 		idmapdlog(LOG_ERR, "%s: database error (%s)", me,
3153 		    CHECK_NULL(errmsg));
3154 		sqlite_freemem(errmsg);
3155 		goto out;
3156 	}
3157 
3158 	for (;;) {
3159 		r = sqlite_step(vm, &ncol, &values, NULL);
3160 		assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
3161 
3162 		if (r == SQLITE_ROW) {
3163 			if (ncol < 5) {
3164 				retcode = IDMAP_ERR_INTERNAL;
3165 				goto out;
3166 			}
3167 
3168 			TRACE(req, res, "Matching rule: %s@%s -> %s",
3169 			    values[2] == NULL ? "(null)" : values[2],
3170 			    values[3] == NULL ? "(null)" : values[3],
3171 			    values[0] == NULL ? "(null)" : values[0]);
3172 
3173 			if (values[0] == NULL) {
3174 				retcode = IDMAP_ERR_INTERNAL;
3175 				goto out;
3176 			}
3177 
3178 			if (values[1] != NULL)
3179 				direction =
3180 				    (strtol(values[1], &end, 10) == 0)?
3181 				    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
3182 			else
3183 				direction = IDMAP_DIRECTION_W2U;
3184 
3185 			if (EMPTY_NAME(values[0])) {
3186 				TRACE(req, res, "Mapping inhibited");
3187 				idmap_namerule_set(rule, values[3], values[2],
3188 				    values[0], is_user, is_wuser,
3189 				    strtol(values[4], &end, 10),
3190 				    direction);
3191 				retcode = IDMAP_ERR_NOMAPPING;
3192 				goto out;
3193 			}
3194 
3195 			if (values[0][0] == '*') {
3196 				unixname = winname;
3197 				lower_unixname = lower_winname;
3198 			} else {
3199 				unixname = values[0];
3200 				lower_unixname = NULL;
3201 			}
3202 
3203 			retcode = ns_lookup_byname(unixname, lower_unixname,
3204 			    &res->id);
3205 			if (retcode == IDMAP_SUCCESS) {
3206 				break;
3207 			} else if (retcode == IDMAP_ERR_NOTFOUND) {
3208 				if (values[0][0] == '*') {
3209 					TRACE(req, res,
3210 					    "%s not found, continuing",
3211 					    unixname);
3212 					/* Case 4 */
3213 					continue;
3214 				} else {
3215 					TRACE(req, res,
3216 					    "%s not found, error", unixname);
3217 					/* Case 3 */
3218 					idmap_namerule_set(rule, values[3],
3219 					    values[2], values[0], is_user,
3220 					    is_wuser,
3221 					    strtol(values[4], &end, 10),
3222 					    direction);
3223 					retcode = IDMAP_ERR_NOMAPPING;
3224 				}
3225 			} else {
3226 				TRACE(req, res, "Looking up %s error=%d",
3227 				    unixname, retcode);
3228 			}
3229 			goto out;
3230 		} else if (r == SQLITE_DONE) {
3231 			TRACE(req, res, "No matching rule");
3232 			retcode = IDMAP_ERR_NOTFOUND;
3233 			goto out;
3234 		} else {
3235 			(void) sqlite_finalize(vm, &errmsg);
3236 			vm = NULL;
3237 			idmapdlog(LOG_ERR, "%s: database error (%s)", me,
3238 			    CHECK_NULL(errmsg));
3239 			sqlite_freemem(errmsg);
3240 			retcode = IDMAP_ERR_INTERNAL;
3241 			goto out;
3242 		}
3243 	}
3244 
3245 	/* Found */
3246 
3247 	if (values[1] != NULL)
3248 		res->direction =
3249 		    (strtol(values[1], &end, 10) == 0)?
3250 		    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
3251 	else
3252 		res->direction = IDMAP_DIRECTION_W2U;
3253 
3254 	req->id2name = strdup(unixname);
3255 	if (req->id2name == NULL) {
3256 		retcode = IDMAP_ERR_MEMORY;
3257 		goto out;
3258 	}
3259 	TRACE(req, res, "UNIX name found");
3260 
3261 	idmap_namerule_set(rule, values[3], values[2],
3262 	    values[0], is_user, is_wuser, strtol(values[4], &end, 10),
3263 	    res->direction);
3264 
3265 out:
3266 	if (retcode != IDMAP_SUCCESS &&
3267 	    retcode != IDMAP_ERR_NOTFOUND &&
3268 	    retcode != IDMAP_ERR_NOMAPPING) {
3269 		TRACE(req, res, "Rule processing error, code=%d", retcode);
3270 	}
3271 
3272 	if (sql != NULL)
3273 		sqlite_freemem(sql);
3274 
3275 	if (retcode != IDMAP_ERR_NOTFOUND) {
3276 		res->info.how.map_type = IDMAP_MAP_TYPE_RULE_BASED;
3277 		res->info.src = IDMAP_MAP_SRC_NEW;
3278 	}
3279 
3280 	if (lower_winname != NULL && lower_winname != winname)
3281 		free(lower_winname);
3282 	if (vm != NULL)
3283 		(void) sqlite_finalize(vm, NULL);
3284 	return (retcode);
3285 }
3286 
3287 static
3288 int
get_next_eph_uid(uid_t * next_uid)3289 get_next_eph_uid(uid_t *next_uid)
3290 {
3291 	uid_t uid;
3292 	gid_t gid;
3293 	int err;
3294 
3295 	*next_uid = (uid_t)-1;
3296 	pthread_mutex_lock(&_idmapdstate.id_lock);
3297 	uid = _idmapdstate.next_uid++;
3298 	if (uid >= _idmapdstate.limit_uid) {
3299 		if ((err = allocids(0, 8192, &uid, 0, &gid)) != 0) {
3300 			pthread_mutex_unlock(&_idmapdstate.id_lock);
3301 			return (err);
3302 		}
3303 		_idmapdstate.limit_uid = uid + 8192;
3304 		_idmapdstate.next_uid = uid + 1;
3305 	}
3306 	pthread_mutex_unlock(&_idmapdstate.id_lock);
3307 	*next_uid = uid;
3308 
3309 	return (0);
3310 }
3311 
3312 static
3313 int
get_next_eph_gid(gid_t * next_gid)3314 get_next_eph_gid(gid_t *next_gid)
3315 {
3316 	uid_t uid;
3317 	gid_t gid;
3318 	int err;
3319 
3320 	*next_gid = (uid_t)-1;
3321 	pthread_mutex_lock(&_idmapdstate.id_lock);
3322 	gid = _idmapdstate.next_gid++;
3323 	if (gid >= _idmapdstate.limit_gid) {
3324 		if ((err = allocids(0, 0, &uid, 8192, &gid)) != 0) {
3325 			pthread_mutex_unlock(&_idmapdstate.id_lock);
3326 			return (err);
3327 		}
3328 		_idmapdstate.limit_gid = gid + 8192;
3329 		_idmapdstate.next_gid = gid + 1;
3330 	}
3331 	pthread_mutex_unlock(&_idmapdstate.id_lock);
3332 	*next_gid = gid;
3333 
3334 	return (0);
3335 }
3336 
3337 static
3338 int
gethash(const char * str,uint32_t num,uint_t htsize)3339 gethash(const char *str, uint32_t num, uint_t htsize)
3340 {
3341 	uint_t  hval, i, len;
3342 
3343 	if (str == NULL)
3344 		return (0);
3345 	for (len = strlen(str), hval = 0, i = 0; i < len; i++) {
3346 		hval += str[i];
3347 		hval += (hval << 10);
3348 		hval ^= (hval >> 6);
3349 	}
3350 	for (str = (const char *)&num, i = 0; i < sizeof (num); i++) {
3351 		hval += str[i];
3352 		hval += (hval << 10);
3353 		hval ^= (hval >> 6);
3354 	}
3355 	hval += (hval << 3);
3356 	hval ^= (hval >> 11);
3357 	hval += (hval << 15);
3358 	return (hval % htsize);
3359 }
3360 
3361 static
3362 int
get_from_sid_history(lookup_state_t * state,const char * prefix,uint32_t rid,uid_t * pid)3363 get_from_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid,
3364     uid_t *pid)
3365 {
3366 	uint_t		next, key;
3367 	uint_t		htsize = state->sid_history_size;
3368 	idmap_sid	*sid;
3369 
3370 	next = gethash(prefix, rid, htsize);
3371 	while (next != htsize) {
3372 		key = state->sid_history[next].key;
3373 		if (key == htsize)
3374 			return (0);
3375 		sid = &state->batch->idmap_mapping_batch_val[key].id1.
3376 		    idmap_id_u.sid;
3377 		if (sid->rid == rid && strcmp(sid->prefix, prefix) == 0) {
3378 			*pid = state->result->ids.ids_val[key].id.
3379 			    idmap_id_u.uid;
3380 			return (1);
3381 		}
3382 		next = state->sid_history[next].next;
3383 	}
3384 	return (0);
3385 }
3386 
3387 static
3388 void
add_to_sid_history(lookup_state_t * state,const char * prefix,uint32_t rid)3389 add_to_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid)
3390 {
3391 	uint_t		hash, next;
3392 	uint_t		htsize = state->sid_history_size;
3393 
3394 	hash = next = gethash(prefix, rid, htsize);
3395 	while (state->sid_history[next].key != htsize) {
3396 		next++;
3397 		next %= htsize;
3398 	}
3399 	state->sid_history[next].key = state->curpos;
3400 	if (hash == next)
3401 		return;
3402 	state->sid_history[next].next = state->sid_history[hash].next;
3403 	state->sid_history[hash].next = next;
3404 }
3405 
3406 void
cleanup_lookup_state(lookup_state_t * state)3407 cleanup_lookup_state(lookup_state_t *state)
3408 {
3409 	free(state->sid_history);
3410 	free(state->ad_unixuser_attr);
3411 	free(state->ad_unixgroup_attr);
3412 	free(state->nldap_winname_attr);
3413 	free(state->defdom);
3414 }
3415 
3416 /* ARGSUSED */
3417 static
3418 idmap_retcode
dynamic_ephemeral_mapping(lookup_state_t * state,idmap_mapping * req,idmap_id_res * res)3419 dynamic_ephemeral_mapping(lookup_state_t *state,
3420     idmap_mapping *req, idmap_id_res *res)
3421 {
3422 
3423 	uid_t		next_pid;
3424 
3425 	res->direction = IDMAP_DIRECTION_BI;
3426 
3427 	if (IDMAP_ID_IS_EPHEMERAL(res->id.idmap_id_u.uid)) {
3428 		res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
3429 		res->info.src = IDMAP_MAP_SRC_CACHE;
3430 		return (IDMAP_SUCCESS);
3431 	}
3432 
3433 	if (state->sid_history != NULL &&
3434 	    get_from_sid_history(state, req->id1.idmap_id_u.sid.prefix,
3435 	    req->id1.idmap_id_u.sid.rid, &next_pid)) {
3436 		res->id.idmap_id_u.uid = next_pid;
3437 		res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
3438 		res->info.src = IDMAP_MAP_SRC_NEW;
3439 		return (IDMAP_SUCCESS);
3440 	}
3441 
3442 	if (res->id.idtype == IDMAP_UID) {
3443 		if (get_next_eph_uid(&next_pid) != 0)
3444 			return (IDMAP_ERR_INTERNAL);
3445 		res->id.idmap_id_u.uid = next_pid;
3446 	} else {
3447 		if (get_next_eph_gid(&next_pid) != 0)
3448 			return (IDMAP_ERR_INTERNAL);
3449 		res->id.idmap_id_u.gid = next_pid;
3450 	}
3451 
3452 	res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
3453 	res->info.src = IDMAP_MAP_SRC_NEW;
3454 	if (state->sid_history != NULL)
3455 		add_to_sid_history(state, req->id1.idmap_id_u.sid.prefix,
3456 		    req->id1.idmap_id_u.sid.rid);
3457 
3458 	return (IDMAP_SUCCESS);
3459 }
3460 
3461 idmap_retcode
sid2pid_second_pass(lookup_state_t * state,idmap_mapping * req,idmap_id_res * res)3462 sid2pid_second_pass(lookup_state_t *state,
3463     idmap_mapping *req, idmap_id_res *res)
3464 {
3465 	idmap_retcode	retcode;
3466 	idmap_retcode	retcode2;
3467 
3468 	/* Check if second pass is needed */
3469 	if (ARE_WE_DONE(req->direction))
3470 		return (res->retcode);
3471 
3472 	/* Get status from previous pass */
3473 	retcode = res->retcode;
3474 	if (retcode != IDMAP_SUCCESS && state->eph_map_unres_sids &&
3475 	    !EMPTY_STRING(req->id1.idmap_id_u.sid.prefix) &&
3476 	    EMPTY_STRING(req->id1name)) {
3477 		/*
3478 		 * We are asked to map an unresolvable SID to a UID or
3479 		 * GID, but, which?  We'll treat all unresolvable SIDs
3480 		 * as users unless the caller specified which of a UID
3481 		 * or GID they want.
3482 		 */
3483 		if (req->id1.idtype == IDMAP_SID)
3484 			req->id1.idtype = IDMAP_USID;
3485 		if (res->id.idtype == IDMAP_POSIXID) {
3486 			res->id.idtype = IDMAP_UID;
3487 			TRACE(req, res, "Assume unresolvable SID is user");
3488 		} else if (res->id.idtype == IDMAP_UID) {
3489 			TRACE(req, res, "Must map unresolvable SID to user");
3490 		} else if (res->id.idtype == IDMAP_GID) {
3491 			TRACE(req, res, "Must map unresolvable SID to group");
3492 		}
3493 		goto do_eph;
3494 	}
3495 	if (retcode != IDMAP_SUCCESS)
3496 		goto out;
3497 
3498 	/*
3499 	 * There are two ways we might get here with a Posix ID:
3500 	 * - It could be from an expired ephemeral cache entry.
3501 	 * - It could be from IDMU.
3502 	 * If it's from IDMU, we need to look up the name, for name-based
3503 	 * requests and the cache.
3504 	 */
3505 	if (!IDMAP_ID_IS_EPHEMERAL(res->id.idmap_id_u.uid) &&
3506 	    res->id.idmap_id_u.uid != IDMAP_SENTINEL_PID) {
3507 		if (req->id2name == NULL) {
3508 			/*
3509 			 * If the lookup fails, go ahead anyway.
3510 			 * The general UNIX rule is that it's OK to
3511 			 * have a UID or GID that isn't in the
3512 			 * name service.
3513 			 */
3514 			retcode2 = ns_lookup_bypid(res->id.idmap_id_u.uid,
3515 			    res->id.idtype == IDMAP_UID, &req->id2name);
3516 			if (IDMAP_ERROR(retcode2)) {
3517 				TRACE(req, res,
3518 				    "Getting UNIX name, error=%d (ignored)",
3519 				    retcode2);
3520 			} else {
3521 				TRACE(req, res, "Found UNIX name");
3522 			}
3523 		}
3524 		goto out;
3525 	}
3526 
3527 	/*
3528 	 * If directory-based name mapping is enabled then the unixname
3529 	 * may already have been retrieved from the AD object (AD-mode or
3530 	 * mixed-mode) or from native LDAP object (nldap-mode) -- done.
3531 	 */
3532 	if (req->id2name != NULL) {
3533 		assert(res->id.idtype != IDMAP_POSIXID);
3534 		if (AD_MODE(res->id.idtype, state))
3535 			res->direction = IDMAP_DIRECTION_BI;
3536 		else if (NLDAP_MODE(res->id.idtype, state))
3537 			res->direction = IDMAP_DIRECTION_BI;
3538 		else if (MIXED_MODE(res->id.idtype, state))
3539 			res->direction = IDMAP_DIRECTION_W2U;
3540 
3541 		/*
3542 		 * Special case: (1) If the ad_unixuser_attr and
3543 		 * ad_unixgroup_attr uses the same attribute
3544 		 * name and (2) if this is a diagonal mapping
3545 		 * request and (3) the unixname has been retrieved
3546 		 * from the AD object -- then we ignore it and fallback
3547 		 * to name-based mapping rules and ephemeral mapping
3548 		 *
3549 		 * Example:
3550 		 *  Properties:
3551 		 *    config/ad_unixuser_attr = "unixname"
3552 		 *    config/ad_unixgroup_attr = "unixname"
3553 		 *  AD user object:
3554 		 *    dn: cn=bob ...
3555 		 *    objectclass: user
3556 		 *    sam: bob
3557 		 *    unixname: bob1234
3558 		 *  AD group object:
3559 		 *    dn: cn=winadmins ...
3560 		 *    objectclass: group
3561 		 *    sam: winadmins
3562 		 *    unixname: unixadmins
3563 		 *
3564 		 *  In this example whether "unixname" refers to a unixuser
3565 		 *  or unixgroup depends upon the AD object.
3566 		 *
3567 		 * $idmap show -c winname:bob gid
3568 		 *    AD lookup by "samAccountName=bob" for
3569 		 *    "ad_unixgroup_attr (i.e unixname)" for directory-based
3570 		 *    mapping would get "bob1234" which is not what we want.
3571 		 *    Now why not getgrnam_r("bob1234") and use it if it
3572 		 *    is indeed a unixgroup? That's because Unix can have
3573 		 *    users and groups with the same name and we clearly
3574 		 *    don't know the intention of the admin here.
3575 		 *    Therefore we ignore this and fallback to name-based
3576 		 *    mapping rules or ephemeral mapping.
3577 		 */
3578 		if ((AD_MODE(res->id.idtype, state) ||
3579 		    MIXED_MODE(res->id.idtype, state)) &&
3580 		    state->ad_unixuser_attr != NULL &&
3581 		    state->ad_unixgroup_attr != NULL &&
3582 		    strcasecmp(state->ad_unixuser_attr,
3583 		    state->ad_unixgroup_attr) == 0 &&
3584 		    ((req->id1.idtype == IDMAP_USID &&
3585 		    res->id.idtype == IDMAP_GID) ||
3586 		    (req->id1.idtype == IDMAP_GSID &&
3587 		    res->id.idtype == IDMAP_UID))) {
3588 			TRACE(req, res, "Ignoring UNIX name found in AD");
3589 			free(req->id2name);
3590 			req->id2name = NULL;
3591 			res->id.idmap_id_u.uid = IDMAP_SENTINEL_PID;
3592 			/* fallback */
3593 		} else {
3594 			if (res->id.idmap_id_u.uid == IDMAP_SENTINEL_PID) {
3595 				retcode = ns_lookup_byname(req->id2name,
3596 				    NULL, &res->id);
3597 				if (retcode != IDMAP_SUCCESS) {
3598 					/*
3599 					 * If ns_lookup_byname() fails that
3600 					 * means the unixname (req->id2name),
3601 					 * which was obtained from the AD
3602 					 * object by directory-based mapping,
3603 					 * is not a valid Unix user/group and
3604 					 * therefore we return the error to the
3605 					 * client instead of doing rule-based
3606 					 * mapping or ephemeral mapping. This
3607 					 * way the client can detect the issue.
3608 					 */
3609 					TRACE(req, res,
3610 					    "UNIX lookup error=%d", retcode);
3611 					goto out;
3612 				}
3613 				TRACE(req, res, "UNIX lookup");
3614 			}
3615 			goto out;
3616 		}
3617 	}
3618 
3619 	/* Free any mapping info from Directory based mapping */
3620 	if (res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN)
3621 		idmap_how_clear(&res->info.how);
3622 
3623 	/*
3624 	 * If we don't have unixname then evaluate local name-based
3625 	 * mapping rules.
3626 	 */
3627 	retcode = name_based_mapping_sid2pid(state, req, res);
3628 	if (retcode == IDMAP_SUCCESS) {
3629 		TRACE(req, res, "Rule-based mapping");
3630 		goto out;
3631 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
3632 		TRACE(req, res, "Rule-based mapping error=%d", retcode);
3633 		goto out;
3634 	}
3635 
3636 do_eph:
3637 	/* If not found, do ephemeral mapping */
3638 	retcode = dynamic_ephemeral_mapping(state, req, res);
3639 	if (retcode == IDMAP_SUCCESS) {
3640 		TRACE(req, res, "Ephemeral mapping");
3641 		goto out;
3642 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
3643 		TRACE(req, res, "Ephemeral mapping error=%d", retcode);
3644 		goto out;
3645 	}
3646 
3647 out:
3648 	res->retcode = idmap_stat4prot(retcode);
3649 	if (res->retcode != IDMAP_SUCCESS) {
3650 		req->direction = _IDMAP_F_DONE;
3651 		res->id.idmap_id_u.uid = UID_NOBODY;
3652 	}
3653 	if (!ARE_WE_DONE(req->direction))
3654 		state->sid2pid_done = FALSE;
3655 	return (retcode);
3656 }
3657 
3658 idmap_retcode
update_cache_pid2sid(lookup_state_t * state,idmap_mapping * req,idmap_id_res * res)3659 update_cache_pid2sid(lookup_state_t *state,
3660     idmap_mapping *req, idmap_id_res *res)
3661 {
3662 	char		*sql = NULL;
3663 	idmap_retcode	retcode;
3664 	idmap_retcode	retcode2;
3665 	char		*map_dn = NULL;
3666 	char		*map_attr = NULL;
3667 	char		*map_value = NULL;
3668 	char		*map_windomain = NULL;
3669 	char		*map_winname = NULL;
3670 	char		*map_unixname = NULL;
3671 	int		map_is_nt4 = FALSE;
3672 
3673 	/* Check if we need to cache anything */
3674 	if (ARE_WE_DONE(req->direction))
3675 		return (IDMAP_SUCCESS);
3676 
3677 	/* We don't cache negative entries */
3678 	if (res->retcode != IDMAP_SUCCESS)
3679 		return (IDMAP_SUCCESS);
3680 
3681 	assert(res->direction != IDMAP_DIRECTION_UNDEF);
3682 	assert(req->id1.idmap_id_u.uid != IDMAP_SENTINEL_PID);
3683 	assert(res->id.idtype != IDMAP_SID);
3684 
3685 	/*
3686 	 * If we've gotten to this point and we *still* don't know the
3687 	 * unixname, well, we'd like to have it now for the cache.
3688 	 *
3689 	 * If we truly always need it for the cache, we should probably
3690 	 * look it up once at the beginning, rather than "at need" in
3691 	 * several places as is now done.  However, it's not really clear
3692 	 * that we *do* need it in the cache; there's a decent argument
3693 	 * that the cache should contain only SIDs and PIDs, so we'll
3694 	 * leave our options open by doing it "at need" here too.
3695 	 *
3696 	 * If we can't find it... c'est la vie.
3697 	 */
3698 	if (req->id1name == NULL) {
3699 		retcode2 = ns_lookup_bypid(req->id1.idmap_id_u.uid,
3700 		    req->id1.idtype == IDMAP_UID, &req->id1name);
3701 		if (retcode2 == IDMAP_SUCCESS)
3702 			TRACE(req, res, "Found UNIX name");
3703 		else
3704 			TRACE(req, res, "Getting UNIX name error=%d", retcode2);
3705 	}
3706 
3707 	assert(res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN);
3708 	switch (res->info.how.map_type) {
3709 	case IDMAP_MAP_TYPE_DS_AD:
3710 		map_dn = res->info.how.idmap_how_u.ad.dn;
3711 		map_attr = res->info.how.idmap_how_u.ad.attr;
3712 		map_value = res->info.how.idmap_how_u.ad.value;
3713 		break;
3714 
3715 	case IDMAP_MAP_TYPE_DS_NLDAP:
3716 		map_dn = res->info.how.idmap_how_u.nldap.dn;
3717 		map_attr = res->info.how.idmap_how_u.nldap.attr;
3718 		map_value = res->info.how.idmap_how_u.nldap.value;
3719 		break;
3720 
3721 	case IDMAP_MAP_TYPE_RULE_BASED:
3722 		map_windomain = res->info.how.idmap_how_u.rule.windomain;
3723 		map_winname = res->info.how.idmap_how_u.rule.winname;
3724 		map_unixname = res->info.how.idmap_how_u.rule.unixname;
3725 		map_is_nt4 = res->info.how.idmap_how_u.rule.is_nt4;
3726 		break;
3727 
3728 	case IDMAP_MAP_TYPE_EPHEMERAL:
3729 		break;
3730 
3731 	case IDMAP_MAP_TYPE_LOCAL_SID:
3732 		break;
3733 
3734 	case IDMAP_MAP_TYPE_IDMU:
3735 		map_dn = res->info.how.idmap_how_u.idmu.dn;
3736 		map_attr = res->info.how.idmap_how_u.idmu.attr;
3737 		map_value = res->info.how.idmap_how_u.idmu.value;
3738 		break;
3739 
3740 	default:
3741 		/* Don't cache other mapping types */
3742 		assert(FALSE);
3743 	}
3744 
3745 	/*
3746 	 * Using NULL for u2w instead of 0 so that our trigger allows
3747 	 * the same pid to be the destination in multiple entries
3748 	 */
3749 	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
3750 	    "(sidprefix, rid, windomain, canon_winname, pid, unixname, "
3751 	    "is_user, is_wuser, expiration, w2u, u2w, "
3752 	    "map_type, map_dn, map_attr, map_value, map_windomain, "
3753 	    "map_winname, map_unixname, map_is_nt4) "
3754 	    "VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
3755 	    "strftime('%%s','now') + %u, %q, 1, "
3756 	    "%d, %Q, %Q, %Q, %Q, %Q, %Q, %d); ",
3757 	    res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
3758 	    req->id2domain, req->id2name, req->id1.idmap_id_u.uid,
3759 	    req->id1name, (req->id1.idtype == IDMAP_UID) ? 1 : 0,
3760 	    (res->id.idtype == IDMAP_USID) ? 1 : 0,
3761 	    state->id_cache_timeout,
3762 	    (res->direction == 0) ? "1" : NULL,
3763 	    res->info.how.map_type, map_dn, map_attr, map_value,
3764 	    map_windomain, map_winname, map_unixname, map_is_nt4);
3765 
3766 	if (sql == NULL) {
3767 		retcode = IDMAP_ERR_INTERNAL;
3768 		idmapdlog(LOG_ERR, "Out of memory");
3769 		goto out;
3770 	}
3771 
3772 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
3773 	if (retcode != IDMAP_SUCCESS)
3774 		goto out;
3775 
3776 	state->pid2sid_done = FALSE;
3777 	sqlite_freemem(sql);
3778 	sql = NULL;
3779 
3780 	/* Check if we need to update namecache */
3781 	if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
3782 		goto out;
3783 
3784 	if (req->id2name == NULL)
3785 		goto out;
3786 
3787 	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
3788 	    "(sidprefix, rid, canon_name, domain, type, expiration) "
3789 	    "VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + %u); ",
3790 	    res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
3791 	    req->id2name, req->id2domain,
3792 	    res->id.idtype, state->name_cache_timeout);
3793 
3794 	if (sql == NULL) {
3795 		retcode = IDMAP_ERR_INTERNAL;
3796 		idmapdlog(LOG_ERR, "Out of memory");
3797 		goto out;
3798 	}
3799 
3800 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
3801 
3802 out:
3803 	if (sql != NULL)
3804 		sqlite_freemem(sql);
3805 	return (retcode);
3806 }
3807 
3808 idmap_retcode
update_cache_sid2pid(lookup_state_t * state,idmap_mapping * req,idmap_id_res * res)3809 update_cache_sid2pid(lookup_state_t *state,
3810     idmap_mapping *req, idmap_id_res *res)
3811 {
3812 	char		*sql = NULL;
3813 	idmap_retcode	retcode;
3814 	int		is_eph_user;
3815 	char		*map_dn = NULL;
3816 	char		*map_attr = NULL;
3817 	char		*map_value = NULL;
3818 	char		*map_windomain = NULL;
3819 	char		*map_winname = NULL;
3820 	char		*map_unixname = NULL;
3821 	int		map_is_nt4 = FALSE;
3822 
3823 	/* Check if we need to cache anything */
3824 	if (ARE_WE_DONE(req->direction))
3825 		return (IDMAP_SUCCESS);
3826 
3827 	/* We don't cache negative entries */
3828 	if (res->retcode != IDMAP_SUCCESS)
3829 		return (IDMAP_SUCCESS);
3830 
3831 	if (req->direction & _IDMAP_F_EXP_EPH_UID)
3832 		is_eph_user = 1;
3833 	else if (req->direction & _IDMAP_F_EXP_EPH_GID)
3834 		is_eph_user = 0;
3835 	else
3836 		is_eph_user = -1;
3837 
3838 	if (is_eph_user >= 0 &&
3839 	    !IDMAP_ID_IS_EPHEMERAL(res->id.idmap_id_u.uid)) {
3840 		sql = sqlite_mprintf("UPDATE idmap_cache "
3841 		    "SET w2u = 0 WHERE "
3842 		    "sidprefix = %Q AND rid = %u AND w2u = 1 AND "
3843 		    "pid >= 2147483648 AND is_user = %d;",
3844 		    req->id1.idmap_id_u.sid.prefix,
3845 		    req->id1.idmap_id_u.sid.rid,
3846 		    is_eph_user);
3847 		if (sql == NULL) {
3848 			retcode = IDMAP_ERR_INTERNAL;
3849 			idmapdlog(LOG_ERR, "Out of memory");
3850 			goto out;
3851 		}
3852 
3853 		retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
3854 		if (retcode != IDMAP_SUCCESS)
3855 			goto out;
3856 
3857 		sqlite_freemem(sql);
3858 		sql = NULL;
3859 	}
3860 
3861 	assert(res->direction != IDMAP_DIRECTION_UNDEF);
3862 	assert(res->id.idmap_id_u.uid != IDMAP_SENTINEL_PID);
3863 
3864 	switch (res->info.how.map_type) {
3865 	case IDMAP_MAP_TYPE_DS_AD:
3866 		map_dn = res->info.how.idmap_how_u.ad.dn;
3867 		map_attr = res->info.how.idmap_how_u.ad.attr;
3868 		map_value = res->info.how.idmap_how_u.ad.value;
3869 		break;
3870 
3871 	case IDMAP_MAP_TYPE_DS_NLDAP:
3872 		map_dn = res->info.how.idmap_how_u.nldap.dn;
3873 		map_attr = res->info.how.idmap_how_u.ad.attr;
3874 		map_value = res->info.how.idmap_how_u.nldap.value;
3875 		break;
3876 
3877 	case IDMAP_MAP_TYPE_RULE_BASED:
3878 		map_windomain = res->info.how.idmap_how_u.rule.windomain;
3879 		map_winname = res->info.how.idmap_how_u.rule.winname;
3880 		map_unixname = res->info.how.idmap_how_u.rule.unixname;
3881 		map_is_nt4 = res->info.how.idmap_how_u.rule.is_nt4;
3882 		break;
3883 
3884 	case IDMAP_MAP_TYPE_EPHEMERAL:
3885 		break;
3886 
3887 	case IDMAP_MAP_TYPE_IDMU:
3888 		map_dn = res->info.how.idmap_how_u.idmu.dn;
3889 		map_attr = res->info.how.idmap_how_u.idmu.attr;
3890 		map_value = res->info.how.idmap_how_u.idmu.value;
3891 		break;
3892 
3893 	default:
3894 		/* Don't cache other mapping types */
3895 		assert(FALSE);
3896 	}
3897 
3898 	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
3899 	    "(sidprefix, rid, windomain, canon_winname, pid, unixname, "
3900 	    "is_user, is_wuser, expiration, w2u, u2w, "
3901 	    "map_type, map_dn, map_attr, map_value, map_windomain, "
3902 	    "map_winname, map_unixname, map_is_nt4) "
3903 	    "VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
3904 	    "strftime('%%s','now') + %u, 1, %q, "
3905 	    "%d, %Q, %Q, %Q, %Q, %Q, %Q, %d);",
3906 	    req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
3907 	    (req->id1domain != NULL) ? req->id1domain : "", req->id1name,
3908 	    res->id.idmap_id_u.uid, req->id2name,
3909 	    (res->id.idtype == IDMAP_UID) ? 1 : 0,
3910 	    (req->id1.idtype == IDMAP_USID) ? 1 : 0,
3911 	    state->id_cache_timeout,
3912 	    (res->direction == 0) ? "1" : NULL,
3913 	    res->info.how.map_type, map_dn, map_attr, map_value,
3914 	    map_windomain, map_winname, map_unixname, map_is_nt4);
3915 
3916 	if (sql == NULL) {
3917 		retcode = IDMAP_ERR_INTERNAL;
3918 		idmapdlog(LOG_ERR, "Out of memory");
3919 		goto out;
3920 	}
3921 
3922 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
3923 	if (retcode != IDMAP_SUCCESS)
3924 		goto out;
3925 
3926 	state->sid2pid_done = FALSE;
3927 	sqlite_freemem(sql);
3928 	sql = NULL;
3929 
3930 	/* Check if we need to update namecache */
3931 	if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
3932 		goto out;
3933 
3934 	if (EMPTY_STRING(req->id1name))
3935 		goto out;
3936 
3937 	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
3938 	    "(sidprefix, rid, canon_name, domain, type, expiration) "
3939 	    "VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + %u); ",
3940 	    req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
3941 	    req->id1name, req->id1domain,
3942 	    req->id1.idtype, state->name_cache_timeout);
3943 
3944 	if (sql == NULL) {
3945 		retcode = IDMAP_ERR_INTERNAL;
3946 		idmapdlog(LOG_ERR, "Out of memory");
3947 		goto out;
3948 	}
3949 
3950 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
3951 
3952 out:
3953 	if (sql != NULL)
3954 		sqlite_freemem(sql);
3955 	return (retcode);
3956 }
3957 
3958 static
3959 idmap_retcode
lookup_cache_pid2sid(sqlite * cache,idmap_mapping * req,idmap_id_res * res,int is_user)3960 lookup_cache_pid2sid(sqlite *cache, idmap_mapping *req, idmap_id_res *res,
3961     int is_user)
3962 {
3963 	char		*end;
3964 	char		*sql = NULL;
3965 	const char	**values;
3966 	sqlite_vm	*vm = NULL;
3967 	int		ncol;
3968 	idmap_retcode	retcode = IDMAP_SUCCESS;
3969 	time_t		curtime;
3970 	idmap_id_type	idtype;
3971 
3972 	/* Current time */
3973 	errno = 0;
3974 	if ((curtime = time(NULL)) == (time_t)-1) {
3975 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
3976 		    strerror(errno));
3977 		retcode = IDMAP_ERR_INTERNAL;
3978 		goto out;
3979 	}
3980 
3981 	/* SQL to lookup the cache by pid or by unixname */
3982 	if (req->id1.idmap_id_u.uid != IDMAP_SENTINEL_PID) {
3983 		sql = sqlite_mprintf("SELECT sidprefix, rid, "
3984 		    "canon_winname, windomain, w2u, is_wuser, "
3985 		    "map_type, map_dn, map_attr, map_value, map_windomain, "
3986 		    "map_winname, map_unixname, map_is_nt4 "
3987 		    "FROM idmap_cache WHERE "
3988 		    "pid = %u AND u2w = 1 AND is_user = %d AND "
3989 		    "(pid >= 2147483648 OR "
3990 		    "(expiration = 0 OR expiration ISNULL OR "
3991 		    "expiration > %d));",
3992 		    req->id1.idmap_id_u.uid, is_user, curtime);
3993 	} else if (req->id1name != NULL) {
3994 		sql = sqlite_mprintf("SELECT sidprefix, rid, "
3995 		    "canon_winname, windomain, w2u, is_wuser, "
3996 		    "map_type, map_dn, map_attr, map_value, map_windomain, "
3997 		    "map_winname, map_unixname, map_is_nt4 "
3998 		    "FROM idmap_cache WHERE "
3999 		    "unixname = %Q AND u2w = 1 AND is_user = %d AND "
4000 		    "(pid >= 2147483648 OR "
4001 		    "(expiration = 0 OR expiration ISNULL OR "
4002 		    "expiration > %d));",
4003 		    req->id1name, is_user, curtime);
4004 	} else {
4005 		retcode = IDMAP_ERR_ARG;
4006 		goto out;
4007 	}
4008 
4009 	if (sql == NULL) {
4010 		idmapdlog(LOG_ERR, "Out of memory");
4011 		retcode = IDMAP_ERR_MEMORY;
4012 		goto out;
4013 	}
4014 	retcode = sql_compile_n_step_once(
4015 	    cache, sql, &vm, &ncol, 14, &values);
4016 	sqlite_freemem(sql);
4017 
4018 	if (retcode == IDMAP_ERR_NOTFOUND)
4019 		goto out;
4020 	else if (retcode == IDMAP_SUCCESS) {
4021 		/* sanity checks */
4022 		if (values[0] == NULL || values[1] == NULL) {
4023 			retcode = IDMAP_ERR_CACHE;
4024 			goto out;
4025 		}
4026 
4027 		switch (res->id.idtype) {
4028 		case IDMAP_SID:
4029 		case IDMAP_USID:
4030 		case IDMAP_GSID:
4031 			idtype = strtol(values[5], &end, 10) == 1
4032 			    ? IDMAP_USID : IDMAP_GSID;
4033 
4034 			if (res->id.idtype == IDMAP_USID &&
4035 			    idtype != IDMAP_USID) {
4036 				retcode = IDMAP_ERR_NOTUSER;
4037 				goto out;
4038 			} else if (res->id.idtype == IDMAP_GSID &&
4039 			    idtype != IDMAP_GSID) {
4040 				retcode = IDMAP_ERR_NOTGROUP;
4041 				goto out;
4042 			}
4043 			res->id.idtype = idtype;
4044 
4045 			res->id.idmap_id_u.sid.rid =
4046 			    strtoul(values[1], &end, 10);
4047 			res->id.idmap_id_u.sid.prefix = strdup(values[0]);
4048 			if (res->id.idmap_id_u.sid.prefix == NULL) {
4049 				idmapdlog(LOG_ERR, "Out of memory");
4050 				retcode = IDMAP_ERR_MEMORY;
4051 				goto out;
4052 			}
4053 
4054 			if (values[4] != NULL)
4055 				res->direction =
4056 				    (strtol(values[4], &end, 10) == 0)?
4057 				    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
4058 			else
4059 				res->direction = IDMAP_DIRECTION_U2W;
4060 
4061 			if (values[2] == NULL)
4062 				break;
4063 			req->id2name = strdup(values[2]);
4064 			if (req->id2name == NULL) {
4065 				idmapdlog(LOG_ERR, "Out of memory");
4066 				retcode = IDMAP_ERR_MEMORY;
4067 				goto out;
4068 			}
4069 
4070 			if (values[3] == NULL)
4071 				break;
4072 			req->id2domain = strdup(values[3]);
4073 			if (req->id2domain == NULL) {
4074 				idmapdlog(LOG_ERR, "Out of memory");
4075 				retcode = IDMAP_ERR_MEMORY;
4076 				goto out;
4077 			}
4078 
4079 			break;
4080 		default:
4081 			retcode = IDMAP_ERR_NOTSUPPORTED;
4082 			break;
4083 		}
4084 		if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
4085 			res->info.src = IDMAP_MAP_SRC_CACHE;
4086 			res->info.how.map_type = strtoul(values[6], &end, 10);
4087 			switch (res->info.how.map_type) {
4088 			case IDMAP_MAP_TYPE_DS_AD:
4089 				res->info.how.idmap_how_u.ad.dn =
4090 				    strdup(values[7]);
4091 				res->info.how.idmap_how_u.ad.attr =
4092 				    strdup(values[8]);
4093 				res->info.how.idmap_how_u.ad.value =
4094 				    strdup(values[9]);
4095 				break;
4096 
4097 			case IDMAP_MAP_TYPE_DS_NLDAP:
4098 				res->info.how.idmap_how_u.nldap.dn =
4099 				    strdup(values[7]);
4100 				res->info.how.idmap_how_u.nldap.attr =
4101 				    strdup(values[8]);
4102 				res->info.how.idmap_how_u.nldap.value =
4103 				    strdup(values[9]);
4104 				break;
4105 
4106 			case IDMAP_MAP_TYPE_RULE_BASED:
4107 				res->info.how.idmap_how_u.rule.windomain =
4108 				    strdup(values[10]);
4109 				res->info.how.idmap_how_u.rule.winname =
4110 				    strdup(values[11]);
4111 				res->info.how.idmap_how_u.rule.unixname =
4112 				    strdup(values[12]);
4113 				res->info.how.idmap_how_u.rule.is_nt4 =
4114 				    strtoul(values[13], &end, 10);
4115 				res->info.how.idmap_how_u.rule.is_user =
4116 				    is_user;
4117 				res->info.how.idmap_how_u.rule.is_wuser =
4118 				    strtol(values[5], &end, 10);
4119 				break;
4120 
4121 			case IDMAP_MAP_TYPE_EPHEMERAL:
4122 				break;
4123 
4124 			case IDMAP_MAP_TYPE_LOCAL_SID:
4125 				break;
4126 
4127 			case IDMAP_MAP_TYPE_KNOWN_SID:
4128 				break;
4129 
4130 			case IDMAP_MAP_TYPE_IDMU:
4131 				res->info.how.idmap_how_u.idmu.dn =
4132 				    strdup(values[7]);
4133 				res->info.how.idmap_how_u.idmu.attr =
4134 				    strdup(values[8]);
4135 				res->info.how.idmap_how_u.idmu.value =
4136 				    strdup(values[9]);
4137 				break;
4138 
4139 			default:
4140 				/* Unknown mapping type */
4141 				assert(FALSE);
4142 			}
4143 		}
4144 	}
4145 
4146 out:
4147 	if (vm != NULL)
4148 		(void) sqlite_finalize(vm, NULL);
4149 	return (retcode);
4150 }
4151 
4152 /*
4153  * Given:
4154  * cache	sqlite handle
4155  * name		Windows user name
4156  * domain	Windows domain name
4157  *
4158  * Return:  Error code
4159  *
4160  * *canonname	Canonical name (if canonname is non-NULL) [1]
4161  * *sidprefix	SID prefix [1]
4162  * *rid		RID
4163  * *type	Type of name
4164  *
4165  * [1] malloc'ed, NULL on error
4166  */
4167 static
4168 idmap_retcode
lookup_cache_name2sid(sqlite * cache,const char * name,const char * domain,char ** canonname,char ** sidprefix,idmap_rid_t * rid,idmap_id_type * type)4169 lookup_cache_name2sid(
4170     sqlite *cache,
4171     const char *name,
4172     const char *domain,
4173     char **canonname,
4174     char **sidprefix,
4175     idmap_rid_t *rid,
4176     idmap_id_type *type)
4177 {
4178 	char		*end, *lower_name;
4179 	char		*sql;
4180 	const char	**values;
4181 	sqlite_vm	*vm = NULL;
4182 	int		ncol;
4183 	time_t		curtime;
4184 	idmap_retcode	retcode;
4185 
4186 	*sidprefix = NULL;
4187 	if (canonname != NULL)
4188 		*canonname = NULL;
4189 
4190 	/* Get current time */
4191 	errno = 0;
4192 	if ((curtime = time(NULL)) == (time_t)-1) {
4193 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
4194 		    strerror(errno));
4195 		retcode = IDMAP_ERR_INTERNAL;
4196 		goto out;
4197 	}
4198 
4199 	/* SQL to lookup the cache */
4200 	if ((lower_name = tolower_u8(name)) == NULL)
4201 		lower_name = (char *)name;
4202 	sql = sqlite_mprintf("SELECT sidprefix, rid, type, canon_name "
4203 	    "FROM name_cache WHERE name = %Q AND domain = %Q AND "
4204 	    "(expiration = 0 OR expiration ISNULL OR "
4205 	    "expiration > %d);", lower_name, domain, curtime);
4206 	if (lower_name != name)
4207 		free(lower_name);
4208 	if (sql == NULL) {
4209 		idmapdlog(LOG_ERR, "Out of memory");
4210 		retcode = IDMAP_ERR_MEMORY;
4211 		goto out;
4212 	}
4213 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 4, &values);
4214 
4215 	sqlite_freemem(sql);
4216 
4217 	if (retcode != IDMAP_SUCCESS)
4218 		goto out;
4219 
4220 	if (type != NULL) {
4221 		if (values[2] == NULL) {
4222 			retcode = IDMAP_ERR_CACHE;
4223 			goto out;
4224 		}
4225 		*type = xlate_legacy_type(strtol(values[2], &end, 10));
4226 	}
4227 
4228 	if (values[0] == NULL || values[1] == NULL) {
4229 		retcode = IDMAP_ERR_CACHE;
4230 		goto out;
4231 	}
4232 
4233 	if (canonname != NULL) {
4234 		assert(values[3] != NULL);
4235 		*canonname = strdup(values[3]);
4236 		if (*canonname == NULL) {
4237 			idmapdlog(LOG_ERR, "Out of memory");
4238 			retcode = IDMAP_ERR_MEMORY;
4239 			goto out;
4240 		}
4241 	}
4242 
4243 	*sidprefix = strdup(values[0]);
4244 	if (*sidprefix == NULL) {
4245 		idmapdlog(LOG_ERR, "Out of memory");
4246 		retcode = IDMAP_ERR_MEMORY;
4247 		goto out;
4248 	}
4249 	*rid = strtoul(values[1], &end, 10);
4250 
4251 	retcode = IDMAP_SUCCESS;
4252 
4253 out:
4254 	if (vm != NULL)
4255 		(void) sqlite_finalize(vm, NULL);
4256 
4257 	if (retcode != IDMAP_SUCCESS) {
4258 		free(*sidprefix);
4259 		*sidprefix = NULL;
4260 		if (canonname != NULL) {
4261 			free(*canonname);
4262 			*canonname = NULL;
4263 		}
4264 	}
4265 	return (retcode);
4266 }
4267 
4268 static
4269 idmap_retcode
ad_lookup_by_winname(lookup_state_t * state,const char * name,const char * domain,int esidtype,char ** dn,char ** attr,char ** value,char ** canonname,char ** sidprefix,idmap_rid_t * rid,idmap_id_type * wintype,char ** unixname)4270 ad_lookup_by_winname(lookup_state_t *state,
4271     const char *name, const char *domain, int esidtype,
4272     char **dn, char **attr, char **value, char **canonname,
4273     char **sidprefix, idmap_rid_t *rid, idmap_id_type *wintype,
4274     char **unixname)
4275 {
4276 	int			retries;
4277 	idmap_query_state_t	*qs = NULL;
4278 	idmap_retcode		rc, retcode;
4279 	int			i;
4280 	int			found_ad = 0;
4281 
4282 	RDLOCK_CONFIG();
4283 	if (_idmapdstate.num_gcs > 0) {
4284 		for (i = 0; i < _idmapdstate.num_gcs && !found_ad; i++) {
4285 			retries = 0;
4286 retry:
4287 			retcode = idmap_lookup_batch_start(
4288 			    _idmapdstate.gcs[i],
4289 			    1,
4290 			    _idmapdstate.cfg->pgcfg.directory_based_mapping,
4291 			    _idmapdstate.cfg->pgcfg.default_domain,
4292 			    &qs);
4293 			if (retcode != IDMAP_SUCCESS) {
4294 				if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR &&
4295 				    retries++ < ADUTILS_DEF_NUM_RETRIES)
4296 					goto retry;
4297 				degrade_svc(1, "failed to create request for "
4298 				    "AD lookup by winname");
4299 				UNLOCK_CONFIG();
4300 				return (retcode);
4301 			}
4302 
4303 			restore_svc();
4304 
4305 			if (state != NULL && i == 0) {
4306 				/*
4307 				 * Directory based name mapping is only
4308 				 * performed within the joined forest (i == 0).
4309 				 * We don't trust other "trusted" forests to
4310 				 * provide DS-based name mapping information
4311 				 * because AD's definition of "cross-forest
4312 				 * trust" does not encompass this sort of
4313 				 * behavior.
4314 				 */
4315 				idmap_lookup_batch_set_unixattr(qs,
4316 				    state->ad_unixuser_attr,
4317 				    state->ad_unixgroup_attr);
4318 			}
4319 
4320 			retcode = idmap_name2sid_batch_add1(qs, name, domain,
4321 			    esidtype, dn, attr, value, canonname, sidprefix,
4322 			    rid, wintype, unixname, NULL, &rc);
4323 			if (retcode == IDMAP_ERR_DOMAIN_NOTFOUND) {
4324 				idmap_lookup_release_batch(&qs);
4325 				continue;
4326 			}
4327 			found_ad = 1;
4328 			if (retcode != IDMAP_SUCCESS)
4329 				idmap_lookup_release_batch(&qs);
4330 			else
4331 				retcode = idmap_lookup_batch_end(&qs);
4332 
4333 			if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR &&
4334 			    retries++ < ADUTILS_DEF_NUM_RETRIES)
4335 				goto retry;
4336 			else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
4337 				degrade_svc(1,
4338 				    "some AD lookups timed out repeatedly");
4339 		}
4340 	} else {
4341 		/* No AD case */
4342 		retcode = IDMAP_ERR_NO_ACTIVEDIRECTORY;
4343 	}
4344 	UNLOCK_CONFIG();
4345 
4346 	if (retcode != IDMAP_SUCCESS) {
4347 		idmapdlog(LOG_NOTICE,
4348 		    "AD lookup of winname %s@%s failed, error code %d",
4349 		    name == NULL ? "(null)" : name,
4350 		    domain == NULL ? "(null)" : domain,
4351 		    retcode);
4352 		return (retcode);
4353 	}
4354 	return (rc);
4355 }
4356 
4357 /*
4358  * Given:
4359  * cache	sqlite handle to cache
4360  * name		Windows user name
4361  * domain	Windows domain name
4362  * local_only	if true, don't try AD lookups
4363  *
4364  * Returns: Error code
4365  *
4366  * *canonname	Canonical name (if non-NULL) [1]
4367  * *canondomain	Canonical domain (if non-NULL) [1]
4368  * *sidprefix	SID prefix [1]
4369  * *rid		RID
4370  * *req		Request (direction is updated)
4371  *
4372  * [1] malloc'ed, NULL on error
4373  */
4374 idmap_retcode
lookup_name2sid(sqlite * cache,const char * name,const char * domain,int want_wuser,char ** canonname,char ** canondomain,char ** sidprefix,idmap_rid_t * rid,idmap_id_type * type,idmap_mapping * req,int local_only)4375 lookup_name2sid(
4376     sqlite *cache,
4377     const char *name,
4378     const char *domain,
4379     int want_wuser,
4380     char **canonname,
4381     char **canondomain,
4382     char **sidprefix,
4383     idmap_rid_t *rid,
4384     idmap_id_type *type,
4385     idmap_mapping *req,
4386     int local_only)
4387 {
4388 	idmap_retcode	retcode;
4389 
4390 	*sidprefix = NULL;
4391 	if (canonname != NULL)
4392 		*canonname = NULL;
4393 	if (canondomain != NULL)
4394 		*canondomain = NULL;
4395 
4396 	/* Lookup well-known SIDs table */
4397 	retcode = lookup_wksids_name2sid(name, domain, canonname, canondomain,
4398 	    sidprefix, rid, type);
4399 	if (retcode == IDMAP_SUCCESS) {
4400 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
4401 		goto out;
4402 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
4403 		return (retcode);
4404 	}
4405 
4406 	/* Lookup cache */
4407 	retcode = lookup_cache_name2sid(cache, name, domain, canonname,
4408 	    sidprefix, rid, type);
4409 	if (retcode == IDMAP_SUCCESS) {
4410 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
4411 		goto out;
4412 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
4413 		return (retcode);
4414 	}
4415 
4416 	/*
4417 	 * The caller may be using this function to determine if this
4418 	 * request needs to be marked for AD lookup or not
4419 	 * (i.e. _IDMAP_F_LOOKUP_AD) and therefore may not want this
4420 	 * function to AD lookup now.
4421 	 */
4422 	if (local_only)
4423 		return (retcode);
4424 
4425 	if (_idmapdstate.cfg->pgcfg.use_lsa &&
4426 	    _idmapdstate.cfg->pgcfg.domain_name != NULL &&
4427 	    name != NULL && *sidprefix == NULL) {
4428 		retcode = lookup_lsa_by_name(name, domain,
4429 		    sidprefix, rid,
4430 		    canonname, canondomain,
4431 		    type);
4432 		if (retcode == IDMAP_SUCCESS)
4433 			goto out;
4434 		else if (retcode != IDMAP_ERR_NOTFOUND)
4435 			return (retcode);
4436 	}
4437 
4438 	/* Lookup AD */
4439 	retcode = ad_lookup_by_winname(NULL, name, domain, IDMAP_POSIXID,
4440 	    NULL, NULL, NULL, canonname, sidprefix, rid, type, NULL);
4441 	if (retcode != IDMAP_SUCCESS)
4442 		return (retcode);
4443 
4444 out:
4445 	/*
4446 	 * Entry found (cache or Windows lookup)
4447 	 */
4448 	if (want_wuser == 1 && *type != IDMAP_USID)
4449 		retcode = IDMAP_ERR_NOTUSER;
4450 	else if (want_wuser == 0 && *type != IDMAP_GSID)
4451 		retcode = IDMAP_ERR_NOTGROUP;
4452 	else if (want_wuser == -1) {
4453 		/*
4454 		 * Caller wants to know if its user or group
4455 		 * Verify that it's one or the other.
4456 		 */
4457 		if (*type != IDMAP_USID && *type != IDMAP_GSID)
4458 			retcode = IDMAP_ERR_SID;
4459 	}
4460 
4461 	if (retcode == IDMAP_SUCCESS) {
4462 		/*
4463 		 * If we were asked for a canonical domain and none
4464 		 * of the searches have provided one, assume it's the
4465 		 * supplied domain.
4466 		 */
4467 		if (canondomain != NULL && *canondomain == NULL) {
4468 			*canondomain = strdup(domain);
4469 			if (*canondomain == NULL)
4470 				retcode = IDMAP_ERR_MEMORY;
4471 		}
4472 	}
4473 	if (retcode != IDMAP_SUCCESS) {
4474 		free(*sidprefix);
4475 		*sidprefix = NULL;
4476 		if (canonname != NULL) {
4477 			free(*canonname);
4478 			*canonname = NULL;
4479 		}
4480 		if (canondomain != NULL) {
4481 			free(*canondomain);
4482 			*canondomain = NULL;
4483 		}
4484 	}
4485 	return (retcode);
4486 }
4487 
4488 static
4489 idmap_retcode
name_based_mapping_pid2sid(lookup_state_t * state,const char * unixname,int is_user,idmap_mapping * req,idmap_id_res * res)4490 name_based_mapping_pid2sid(lookup_state_t *state, const char *unixname,
4491     int is_user, idmap_mapping *req, idmap_id_res *res)
4492 {
4493 	const char	*winname, *windomain;
4494 	char		*canonname;
4495 	char		*canondomain;
4496 	char		*sql = NULL, *errmsg = NULL;
4497 	idmap_retcode	retcode;
4498 	char		*end;
4499 	const char	**values;
4500 	sqlite_vm	*vm = NULL;
4501 	int		ncol, r;
4502 	int		want_wuser;
4503 	const char	*me = "name_based_mapping_pid2sid";
4504 	idmap_namerule	*rule = &res->info.how.idmap_how_u.rule;
4505 	int direction;
4506 
4507 	assert(unixname != NULL); /* We have unixname */
4508 	assert(req->id2name == NULL); /* We don't have winname */
4509 	assert(res->id.idmap_id_u.sid.prefix == NULL); /* No SID either */
4510 
4511 	sql = sqlite_mprintf(
4512 	    "SELECT winname_display, windomain, w2u_order, "
4513 	    "is_wuser, unixname, is_nt4 "
4514 	    "FROM namerules WHERE "
4515 	    "u2w_order > 0 AND is_user = %d AND "
4516 	    "(unixname = %Q OR unixname = '*') "
4517 	    "ORDER BY u2w_order ASC;", is_user, unixname);
4518 	if (sql == NULL) {
4519 		idmapdlog(LOG_ERR, "Out of memory");
4520 		retcode = IDMAP_ERR_MEMORY;
4521 		goto out;
4522 	}
4523 
4524 	if (sqlite_compile(state->db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
4525 		retcode = IDMAP_ERR_INTERNAL;
4526 		idmapdlog(LOG_ERR, "%s: database error (%s)", me,
4527 		    CHECK_NULL(errmsg));
4528 		sqlite_freemem(errmsg);
4529 		goto out;
4530 	}
4531 
4532 	for (;;) {
4533 		r = sqlite_step(vm, &ncol, &values, NULL);
4534 		assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
4535 		if (r == SQLITE_ROW) {
4536 			if (ncol < 6) {
4537 				retcode = IDMAP_ERR_INTERNAL;
4538 				goto out;
4539 			}
4540 
4541 			TRACE(req, res, "Matching rule: %s -> %s@%s",
4542 			    values[4] == NULL ? "(null)" : values[4],
4543 			    values[0] == NULL ? "(null)" : values[0],
4544 			    values[1] == NULL ? "(null)" : values[1]);
4545 
4546 			if (values[0] == NULL) {
4547 				/* values [1] and [2] can be null */
4548 				retcode = IDMAP_ERR_INTERNAL;
4549 				goto out;
4550 			}
4551 
4552 			if (values[2] != NULL)
4553 				direction =
4554 				    (strtol(values[2], &end, 10) == 0)?
4555 				    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
4556 			else
4557 				direction = IDMAP_DIRECTION_U2W;
4558 
4559 			if (EMPTY_NAME(values[0])) {
4560 				idmap_namerule_set(rule, values[1], values[0],
4561 				    values[4], is_user,
4562 				    strtol(values[3], &end, 10),
4563 				    strtol(values[5], &end, 10),
4564 				    direction);
4565 				TRACE(req, res, "Mapping inhibited");
4566 				retcode = IDMAP_ERR_NOMAPPING;
4567 				goto out;
4568 			}
4569 
4570 			if (values[0][0] == '*') {
4571 				winname = unixname;
4572 			} else {
4573 				winname = values[0];
4574 			}
4575 
4576 			want_wuser = res->id.idtype == IDMAP_USID ? 1
4577 			    : res->id.idtype == IDMAP_GSID ? 0
4578 			    : -1;
4579 			if (values[1] != NULL)
4580 				windomain = values[1];
4581 			else if (state->defdom != NULL) {
4582 				windomain = state->defdom;
4583 				TRACE(req, res,
4584 				    "Added default domain %s to rule",
4585 				    windomain);
4586 			} else {
4587 				idmapdlog(LOG_ERR, "%s: no domain", me);
4588 				TRACE(req, res,
4589 				    "No domain in rule, and no default domain");
4590 				retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
4591 				goto out;
4592 			}
4593 
4594 			retcode = lookup_name2sid(state->cache,
4595 			    winname, windomain,
4596 			    want_wuser, &canonname, &canondomain,
4597 			    &res->id.idmap_id_u.sid.prefix,
4598 			    &res->id.idmap_id_u.sid.rid,
4599 			    &res->id.idtype, req, 0);
4600 
4601 			if (retcode == IDMAP_SUCCESS) {
4602 				break;
4603 			} else if (retcode == IDMAP_ERR_NOTFOUND) {
4604 				if (values[0][0] == '*') {
4605 					TRACE(req, res,
4606 					    "%s@%s not found, continuing",
4607 					    winname, windomain);
4608 					continue;
4609 				} else {
4610 					TRACE(req, res,
4611 					    "%s@%s not found",
4612 					    winname, windomain);
4613 					retcode = IDMAP_ERR_NOMAPPING;
4614 				}
4615 			} else {
4616 				TRACE(req, res,
4617 				    "Looking up %s@%s error=%d",
4618 				    winname, windomain, retcode);
4619 			}
4620 
4621 			idmap_namerule_set(rule, values[1],
4622 			    values[0], values[4], is_user,
4623 			    strtol(values[3], &end, 10),
4624 			    strtol(values[5], &end, 10),
4625 			    direction);
4626 
4627 			goto out;
4628 
4629 		} else if (r == SQLITE_DONE) {
4630 			TRACE(req, res, "No matching rule");
4631 			retcode = IDMAP_ERR_NOTFOUND;
4632 			goto out;
4633 		} else {
4634 			(void) sqlite_finalize(vm, &errmsg);
4635 			vm = NULL;
4636 			idmapdlog(LOG_ERR, "%s: database error (%s)", me,
4637 			    CHECK_NULL(errmsg));
4638 			sqlite_freemem(errmsg);
4639 			retcode = IDMAP_ERR_INTERNAL;
4640 			goto out;
4641 		}
4642 	}
4643 
4644 	if (values[2] != NULL)
4645 		res->direction =
4646 		    (strtol(values[2], &end, 10) == 0)?
4647 		    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
4648 	else
4649 		res->direction = IDMAP_DIRECTION_U2W;
4650 
4651 	req->id2name = canonname;
4652 	req->id2domain = canondomain;
4653 
4654 	idmap_namerule_set(rule, values[1], values[0], values[4],
4655 	    is_user, strtol(values[3], &end, 10),
4656 	    strtol(values[5], &end, 10),
4657 	    rule->direction);
4658 	TRACE(req, res, "Windows name found");
4659 
4660 out:
4661 	if (sql != NULL)
4662 		sqlite_freemem(sql);
4663 
4664 	if (retcode != IDMAP_ERR_NOTFOUND) {
4665 		res->info.how.map_type = IDMAP_MAP_TYPE_RULE_BASED;
4666 		res->info.src = IDMAP_MAP_SRC_NEW;
4667 	}
4668 
4669 	if (vm != NULL)
4670 		(void) sqlite_finalize(vm, NULL);
4671 	return (retcode);
4672 }
4673 
4674 /*
4675  * Convention when processing unix2win requests:
4676  *
4677  * Unix identity:
4678  * req->id1name =
4679  *              unixname if given otherwise unixname found will be placed
4680  *              here.
4681  * req->id1domain =
4682  *              NOT USED
4683  * req->id1.idtype =
4684  *              Given type (IDMAP_UID or IDMAP_GID)
4685  * req->id1..[uid or gid] =
4686  *              UID/GID if given otherwise UID/GID found will be placed here.
4687  *
4688  * Windows identity:
4689  * req->id2name =
4690  *              winname found will be placed here.
4691  * req->id2domain =
4692  *              windomain found will be placed here.
4693  * res->id.idtype =
4694  *              Target type initialized from req->id2.idtype. If
4695  *              it is IDMAP_SID then actual type (IDMAP_USID/GSID) found
4696  *              will be placed here.
4697  * req->id..sid.[prefix, rid] =
4698  *              SID found will be placed here.
4699  *
4700  * Others:
4701  * res->retcode =
4702  *              Return status for this request will be placed here.
4703  * res->direction =
4704  *              Direction found will be placed here. Direction
4705  *              meaning whether the resultant mapping is valid
4706  *              only from unix2win or bi-directional.
4707  * req->direction =
4708  *              INTERNAL USE. Used by idmapd to set various
4709  *              flags (_IDMAP_F_xxxx) to aid in processing
4710  *              of the request.
4711  * req->id2.idtype =
4712  *              INTERNAL USE. Initially this is the requested target
4713  *              type and is used to initialize res->id.idtype.
4714  *              ad_lookup_batch() uses this field temporarily to store
4715  *              sid_type obtained by the batched AD lookups and after
4716  *              use resets it to IDMAP_NONE to prevent xdr from
4717  *              mis-interpreting the contents of req->id2.
4718  * req->id2..[uid or gid or sid] =
4719  *              NOT USED
4720  */
4721 
4722 /*
4723  * This function does the following:
4724  * 1. Lookup well-known SIDs table.
4725  * 2. Lookup cache.
4726  * 3. Check if the client does not want new mapping to be allocated
4727  *    in which case this pass is the final pass.
4728  * 4. Set AD/NLDAP lookup flags if it determines that the next stage needs
4729  *    to do AD/NLDAP lookup.
4730  */
4731 idmap_retcode
pid2sid_first_pass(lookup_state_t * state,idmap_mapping * req,idmap_id_res * res,int is_user)4732 pid2sid_first_pass(lookup_state_t *state, idmap_mapping *req,
4733     idmap_id_res *res, int is_user)
4734 {
4735 	idmap_retcode	retcode;
4736 	idmap_retcode	retcode2;
4737 	bool_t		gen_localsid_on_err = FALSE;
4738 
4739 	/* Initialize result */
4740 	res->id.idtype = req->id2.idtype;
4741 	res->direction = IDMAP_DIRECTION_UNDEF;
4742 
4743 	if (req->id2.idmap_id_u.sid.prefix != NULL) {
4744 		/* sanitize sidprefix */
4745 		free(req->id2.idmap_id_u.sid.prefix);
4746 		req->id2.idmap_id_u.sid.prefix = NULL;
4747 	}
4748 
4749 	/* Find pid */
4750 	if (req->id1.idmap_id_u.uid == IDMAP_SENTINEL_PID) {
4751 		if (req->id1name == NULL) {
4752 			retcode = IDMAP_ERR_ARG;
4753 			goto out;
4754 		}
4755 
4756 		retcode = ns_lookup_byname(req->id1name, NULL, &req->id1);
4757 		if (retcode != IDMAP_SUCCESS) {
4758 			TRACE(req, res, "Getting UNIX ID error=%d", retcode);
4759 			retcode = IDMAP_ERR_NOMAPPING;
4760 			goto out;
4761 		}
4762 		TRACE(req, res, "Found UNIX ID");
4763 	}
4764 
4765 	/* Lookup in well-known SIDs table */
4766 	retcode = lookup_wksids_pid2sid(req, res, is_user);
4767 	if (retcode == IDMAP_SUCCESS) {
4768 		TRACE(req, res, "Hardwired mapping");
4769 		goto out;
4770 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
4771 		TRACE(req, res,
4772 		    "Well-known account lookup error=%d", retcode);
4773 		goto out;
4774 	}
4775 
4776 	/* Lookup in cache */
4777 	retcode = lookup_cache_pid2sid(state->cache, req, res, is_user);
4778 	if (retcode == IDMAP_SUCCESS) {
4779 		TRACE(req, res, "Found in mapping cache");
4780 		goto out;
4781 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
4782 		TRACE(req, res,
4783 		    "Mapping cache lookup error=%d", retcode);
4784 		goto out;
4785 	}
4786 	TRACE(req, res, "Not found in mapping cache");
4787 
4788 	/* Ephemeral ids cannot be allocated during pid2sid */
4789 	if (IDMAP_ID_IS_EPHEMERAL(req->id1.idmap_id_u.uid)) {
4790 		retcode = IDMAP_ERR_NOMAPPING;
4791 		TRACE(req, res, "Shouldn't have an ephemeral ID here");
4792 		goto out;
4793 	}
4794 
4795 	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req)) {
4796 		retcode = IDMAP_ERR_NONE_GENERATED;
4797 		goto out;
4798 	}
4799 
4800 	if (AVOID_NAMESERVICE(req)) {
4801 		gen_localsid_on_err = TRUE;
4802 		retcode = IDMAP_ERR_NOMAPPING;
4803 		goto out;
4804 	}
4805 
4806 	/* Set flags for the next stage */
4807 	if (state->directory_based_mapping == DIRECTORY_MAPPING_IDMU) {
4808 		req->direction |= _IDMAP_F_LOOKUP_AD;
4809 		state->ad_nqueries++;
4810 	} else if (AD_MODE(req->id1.idtype, state)) {
4811 		/*
4812 		 * If AD-based name mapping is enabled then the next stage
4813 		 * will need to lookup AD using unixname to get the
4814 		 * corresponding winname.
4815 		 */
4816 		if (req->id1name == NULL) {
4817 			/* Get unixname if only pid is given. */
4818 			retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid,
4819 			    is_user, &req->id1name);
4820 			if (retcode != IDMAP_SUCCESS) {
4821 				TRACE(req, res,
4822 				    "Getting UNIX name error=%d", retcode);
4823 				gen_localsid_on_err = TRUE;
4824 				goto out;
4825 			}
4826 			TRACE(req, res, "Found UNIX name");
4827 		}
4828 		req->direction |= _IDMAP_F_LOOKUP_AD;
4829 		state->ad_nqueries++;
4830 	} else if (NLDAP_OR_MIXED_MODE(req->id1.idtype, state)) {
4831 		/*
4832 		 * If native LDAP or mixed mode is enabled for name mapping
4833 		 * then the next stage will need to lookup native LDAP using
4834 		 * unixname/pid to get the corresponding winname.
4835 		 */
4836 		req->direction |= _IDMAP_F_LOOKUP_NLDAP;
4837 		state->nldap_nqueries++;
4838 	}
4839 
4840 	/*
4841 	 * Failed to find non-expired entry in cache. Set the flag to
4842 	 * indicate that we are not done yet.
4843 	 */
4844 	state->pid2sid_done = FALSE;
4845 	req->direction |= _IDMAP_F_NOTDONE;
4846 	retcode = IDMAP_SUCCESS;
4847 
4848 out:
4849 	res->retcode = idmap_stat4prot(retcode);
4850 	if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS) {
4851 		if (gen_localsid_on_err == TRUE) {
4852 			retcode2 = generate_localsid(req, res, is_user, TRUE);
4853 			if (retcode2 == IDMAP_SUCCESS)
4854 				TRACE(req, res, "Generate local SID");
4855 			else
4856 				TRACE(req, res,
4857 				    "Generate local SID error=%d", retcode2);
4858 		}
4859 	}
4860 	return (retcode);
4861 }
4862 
4863 idmap_retcode
pid2sid_second_pass(lookup_state_t * state,idmap_mapping * req,idmap_id_res * res,int is_user)4864 pid2sid_second_pass(lookup_state_t *state, idmap_mapping *req,
4865     idmap_id_res *res, int is_user)
4866 {
4867 	bool_t		gen_localsid_on_err = TRUE;
4868 	idmap_retcode	retcode = IDMAP_SUCCESS;
4869 	idmap_retcode	retcode2;
4870 
4871 	/* Check if second pass is needed */
4872 	if (ARE_WE_DONE(req->direction))
4873 		return (res->retcode);
4874 
4875 	/* Get status from previous pass */
4876 	retcode = res->retcode;
4877 	if (retcode != IDMAP_SUCCESS)
4878 		goto out;
4879 
4880 	/*
4881 	 * If directory-based name mapping is enabled then the winname
4882 	 * may already have been retrieved from the AD object (AD-mode)
4883 	 * or from native LDAP object (nldap-mode or mixed-mode).
4884 	 * Note that if we have winname but no SID then it's an error
4885 	 * because this implies that the Native LDAP entry contains
4886 	 * winname which does not exist and it's better that we return
4887 	 * an error instead of doing rule-based mapping so that the user
4888 	 * can detect the issue and take appropriate action.
4889 	 */
4890 	if (req->id2name != NULL) {
4891 		/* Return notfound if we've winname but no SID. */
4892 		if (res->id.idmap_id_u.sid.prefix == NULL) {
4893 			TRACE(req, res, "Windows name but no SID");
4894 			retcode = IDMAP_ERR_NOTFOUND;
4895 			goto out;
4896 		}
4897 		if (state->directory_based_mapping == DIRECTORY_MAPPING_IDMU)
4898 			res->direction = IDMAP_DIRECTION_BI;
4899 		else if (AD_MODE(req->id1.idtype, state))
4900 			res->direction = IDMAP_DIRECTION_BI;
4901 		else if (NLDAP_MODE(req->id1.idtype, state))
4902 			res->direction = IDMAP_DIRECTION_BI;
4903 		else if (MIXED_MODE(req->id1.idtype, state))
4904 			res->direction = IDMAP_DIRECTION_W2U;
4905 		goto out;
4906 	} else if (res->id.idmap_id_u.sid.prefix != NULL) {
4907 		/*
4908 		 * We've SID but no winname. This is fine because
4909 		 * the caller may have only requested SID.
4910 		 */
4911 		goto out;
4912 	}
4913 
4914 	/* Free any mapping info from Directory based mapping */
4915 	if (res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN)
4916 		idmap_how_clear(&res->info.how);
4917 
4918 	if (req->id1name == NULL) {
4919 		/* Get unixname from name service */
4920 		retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid, is_user,
4921 		    &req->id1name);
4922 		if (retcode != IDMAP_SUCCESS) {
4923 			TRACE(req, res,
4924 			    "Getting UNIX name error=%d", retcode);
4925 			goto out;
4926 		}
4927 		TRACE(req, res, "Found UNIX name");
4928 	} else if (req->id1.idmap_id_u.uid == IDMAP_SENTINEL_PID) {
4929 		/* Get pid from name service */
4930 		retcode = ns_lookup_byname(req->id1name, NULL, &req->id1);
4931 		if (retcode != IDMAP_SUCCESS) {
4932 			TRACE(req, res,
4933 			    "Getting UNIX ID error=%d", retcode);
4934 			gen_localsid_on_err = FALSE;
4935 			goto out;
4936 		}
4937 		TRACE(req, res, "Found UNIX ID");
4938 	}
4939 
4940 	/* Use unixname to evaluate local name-based mapping rules */
4941 	retcode = name_based_mapping_pid2sid(state, req->id1name, is_user,
4942 	    req, res);
4943 	if (retcode == IDMAP_ERR_NOTFOUND) {
4944 		retcode = generate_localsid(req, res, is_user, FALSE);
4945 		if (retcode == IDMAP_SUCCESS) {
4946 			TRACE(req, res, "Generated local SID");
4947 		} else {
4948 			TRACE(req, res,
4949 			    "Generating local SID error=%d", retcode);
4950 		}
4951 		gen_localsid_on_err = FALSE;
4952 	}
4953 
4954 out:
4955 	res->retcode = idmap_stat4prot(retcode);
4956 	if (res->retcode != IDMAP_SUCCESS) {
4957 		req->direction = _IDMAP_F_DONE;
4958 		free(req->id2name);
4959 		req->id2name = NULL;
4960 		free(req->id2domain);
4961 		req->id2domain = NULL;
4962 		if (gen_localsid_on_err == TRUE) {
4963 			retcode2 = generate_localsid(req, res, is_user, TRUE);
4964 			if (retcode2 == IDMAP_SUCCESS)
4965 				TRACE(req, res, "Generate local SID");
4966 			else
4967 				TRACE(req, res,
4968 				    "Generate local SID error=%d", retcode2);
4969 		} else {
4970 			res->id.idtype = is_user ? IDMAP_USID : IDMAP_GSID;
4971 		}
4972 	}
4973 	if (!ARE_WE_DONE(req->direction))
4974 		state->pid2sid_done = FALSE;
4975 	return (retcode);
4976 }
4977 
4978 idmap_retcode
idmap_cache_flush(idmap_flush_op op)4979 idmap_cache_flush(idmap_flush_op op)
4980 {
4981 	idmap_retcode	rc;
4982 	sqlite *cache = NULL;
4983 	char *sql1;
4984 	char *sql2;
4985 
4986 	switch (op) {
4987 	case IDMAP_FLUSH_EXPIRE:
4988 		sql1 =
4989 		    "UPDATE idmap_cache SET expiration=1 WHERE expiration>0;";
4990 		sql2 =
4991 		    "UPDATE name_cache SET expiration=1 WHERE expiration>0;";
4992 		break;
4993 
4994 	case IDMAP_FLUSH_DELETE:
4995 		sql1 = "DELETE FROM idmap_cache;";
4996 		sql2 = "DELETE FROM name_cache;";
4997 		break;
4998 
4999 	default:
5000 		return (IDMAP_ERR_INTERNAL);
5001 	}
5002 
5003 	rc = get_cache_handle(&cache);
5004 	if (rc != IDMAP_SUCCESS)
5005 		return (rc);
5006 
5007 	/*
5008 	 * Note that we flush the idmapd cache first, before the kernel
5009 	 * cache.  If we did it the other way 'round, a request could come
5010 	 * in after the kernel cache flush and pull a soon-to-be-flushed
5011 	 * idmapd cache entry back into the kernel cache.  This way the
5012 	 * worst that will happen is that a new entry will be added to
5013 	 * the kernel cache and then immediately flushed.
5014 	 */
5015 
5016 	rc = sql_exec_no_cb(cache, IDMAP_CACHENAME, sql1);
5017 	if (rc == IDMAP_SUCCESS)
5018 		rc = sql_exec_no_cb(cache, IDMAP_CACHENAME, sql2);
5019 	if (rc == IDMAP_SUCCESS)
5020 		(void) __idmap_flush_kcache();
5021 
5022 	if (rc == IDMAP_ERR_DB)
5023 		kill_cache_handle(cache);
5024 
5025 	return (rc);
5026 }
5027