1/* Mapping NSS services to action lists.
2 Copyright (C) 2020-2021 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <https://www.gnu.org/licenses/>. */
18
19#include "nss_database.h"
20
21#include <allocate_once.h>
22#include <array_length.h>
23#include <assert.h>
24#include <atomic.h>
25#include <ctype.h>
26#include <file_change_detection.h>
27#include <libc-lock.h>
28#include <netdb.h>
29#include <stdio_ext.h>
30#include <string.h>
31
32struct nss_database_state
33{
34 struct nss_database_data data;
35 __libc_lock_define (, lock);
36 /* If "/" changes, we switched into a container and do NOT want to
37 reload anything. This data must be persistent across
38 reloads. */
39 ino64_t root_ino;
40 dev_t root_dev;
41};
42
43
44/* Global NSS database state. Underlying type is "struct
45 nss_database_state *" but the allocate_once API requires
46 "void *". */
47static void *global_database_state;
48
49/* Allocate and return pointer to nss_database_state object or
50 on failure return NULL. */
51static void *
52global_state_allocate (void *closure)
53{
54 struct nss_database_state *result = malloc (sizeof (*result));
55 if (result != NULL)
56 {
57 result->data.nsswitch_conf.size = -1; /* Force reload. */
58 memset (result->data.services, 0, sizeof (result->data.services));
59 result->data.initialized = true;
60 result->data.reload_disabled = false;
61 __libc_lock_init (result->lock);
62 result->root_ino = 0;
63 result->root_dev = 0;
64 }
65 return result;
66}
67
68/* Return pointer to global NSS database state, allocating as
69 required, or returning NULL on failure. */
70static struct nss_database_state *
71nss_database_state_get (void)
72{
73 return allocate_once (&global_database_state, global_state_allocate,
74 NULL, NULL);
75}
76
77/* Database default selections. nis/compat mappings get turned into
78 "files" for !LINK_OBSOLETE_NSL configurations. */
79enum nss_database_default
80{
81 nss_database_default_defconfig = 0, /* "nis [NOTFOUND=return] files". */
82 nss_database_default_compat, /* "compat [NOTFOUND=return] files". */
83 nss_database_default_dns, /* "dns [!UNAVAIL=return] files". */
84 nss_database_default_files, /* "files". */
85 nss_database_default_nis, /* "nis". */
86 nss_database_default_nis_nisplus, /* "nis nisplus". */
87 nss_database_default_none, /* Empty list. */
88
89 NSS_DATABASE_DEFAULT_COUNT /* Number of defaults. */
90};
91
92/* Databases not listed default to nss_database_default_defconfig. */
93static const char per_database_defaults[NSS_DATABASE_COUNT] =
94 {
95 [nss_database_group] = nss_database_default_compat,
96 [nss_database_gshadow] = nss_database_default_files,
97 [nss_database_hosts] = nss_database_default_dns,
98 [nss_database_initgroups] = nss_database_default_none,
99 [nss_database_networks] = nss_database_default_dns,
100 [nss_database_passwd] = nss_database_default_compat,
101 [nss_database_publickey] = nss_database_default_nis_nisplus,
102 [nss_database_shadow] = nss_database_default_compat,
103 };
104
105struct nss_database_default_cache
106{
107 nss_action_list caches[NSS_DATABASE_DEFAULT_COUNT];
108};
109
110static bool
111nss_database_select_default (struct nss_database_default_cache *cache,
112 enum nss_database db, nss_action_list *result)
113{
114 enum nss_database_default def = per_database_defaults[db];
115 *result = cache->caches[def];
116 if (*result != NULL)
117 return true;
118
119 /* Determine the default line string. */
120 const char *line;
121 switch (def)
122 {
123#ifdef LINK_OBSOLETE_NSL
124 case nss_database_default_defconfig:
125 line = "nis [NOTFOUND=return] files";
126 break;
127 case nss_database_default_compat:
128 line = "compat [NOTFOUND=return] files";
129 break;
130#endif
131
132 case nss_database_default_dns:
133 line = "dns [!UNAVAIL=return] files";
134 break;
135
136 case nss_database_default_files:
137#ifndef LINK_OBSOLETE_NSL
138 case nss_database_default_defconfig:
139 case nss_database_default_compat:
140#endif
141 line = "files";
142 break;
143
144 case nss_database_default_nis:
145 line = "nis";
146 break;
147
148 case nss_database_default_nis_nisplus:
149 line = "nis nisplus";
150 break;
151
152 case nss_database_default_none:
153 /* Very special case: Leave *result as NULL. */
154 return true;
155
156 case NSS_DATABASE_DEFAULT_COUNT:
157 __builtin_unreachable ();
158 }
159 if (def < 0 || def >= NSS_DATABASE_DEFAULT_COUNT)
160 /* Tell GCC that line is initialized. */
161 __builtin_unreachable ();
162
163 *result = __nss_action_parse (line);
164 if (*result == NULL)
165 {
166 assert (errno == ENOMEM);
167 return false;
168 }
169 else
170 return true;
171}
172
173/* database_name must be large enough for each individual name plus a
174 null terminator. */
175typedef char database_name[11];
176#define DEFINE_DATABASE(name) \
177 _Static_assert (sizeof (#name) <= sizeof (database_name), #name);
178#include "databases.def"
179#undef DEFINE_DATABASE
180
181static const database_name nss_database_name_array[] =
182 {
183#define DEFINE_DATABASE(name) #name,
184#include "databases.def"
185#undef DEFINE_DATABASE
186 };
187
188static int
189name_search (const void *left, const void *right)
190{
191 return strcmp (left, right);
192}
193
194static int
195name_to_database_index (const char *name)
196{
197 database_name *name_entry = bsearch (name, nss_database_name_array,
198 array_length (nss_database_name_array),
199 sizeof (database_name), name_search);
200 if (name_entry == NULL)
201 return -1;
202 return name_entry - nss_database_name_array;
203}
204
205static bool
206process_line (struct nss_database_data *data, char *line)
207{
208 /* Ignore leading white spaces. ATTENTION: this is different from
209 what is implemented in Solaris. The Solaris man page says a line
210 beginning with a white space character is ignored. We regard
211 this as just another misfeature in Solaris. */
212 while (isspace (line[0]))
213 ++line;
214
215 /* Recognize `<database> ":"'. */
216 char *name = line;
217 while (line[0] != '\0' && !isspace (line[0]) && line[0] != ':')
218 ++line;
219 if (line[0] == '\0' || name == line)
220 /* Syntax error. Skip this line. */
221 return true;
222 while (line[0] != '\0' && (isspace (line[0]) || line[0] == ':'))
223 *line++ = '\0';
224
225 int db = name_to_database_index (name);
226 if (db < 0)
227 /* Not our database e.g. sudoers, automount, etc. */
228 return true;
229
230 nss_action_list result = __nss_action_parse (line);
231 if (result == NULL)
232 return false;
233 data->services[db] = result;
234 return true;
235}
236
237int
238__nss_configure_lookup (const char *dbname, const char *service_line)
239{
240 int db;
241 nss_action_list result;
242 struct nss_database_state *local;
243
244 /* Convert named database to index. */
245 db = name_to_database_index (dbname);
246 if (db < 0)
247 /* Not our database (e.g., sudoers). */
248 return -1;
249
250 /* Force any load/cache/read whatever to happen, so we can override
251 it. */
252 __nss_database_get (db, &result);
253
254 local = nss_database_state_get ();
255
256 result = __nss_action_parse (service_line);
257 if (result == NULL)
258 return -1;
259
260 atomic_store_release (&local->data.reload_disabled, 1);
261 local->data.services[db] = result;
262
263#ifdef USE_NSCD
264 __nss_database_custom[db] = true;
265#endif
266
267 return 0;
268}
269
270/* Iterate over the lines in FP, parse them, and store them in DATA.
271 Return false on memory allocation failure, true on success. */
272static bool
273nss_database_reload_1 (struct nss_database_data *data, FILE *fp)
274{
275 char *line = NULL;
276 size_t line_allocated = 0;
277 bool result = false;
278
279 while (true)
280 {
281 ssize_t ret = __getline (&line, &line_allocated, fp);
282 if (__ferror_unlocked (fp))
283 break;
284 if (__feof_unlocked (fp))
285 {
286 result = true;
287 break;
288 }
289 assert (ret > 0);
290 (void) ret; /* For NDEBUG builds. */
291
292 if (!process_line (data, line))
293 break;
294 }
295
296 free (line);
297 return result;
298}
299
300static bool
301nss_database_reload (struct nss_database_data *staging,
302 struct file_change_detection *initial)
303{
304 FILE *fp = fopen (_PATH_NSSWITCH_CONF, "rce");
305 if (fp == NULL)
306 switch (errno)
307 {
308 case EACCES:
309 case EISDIR:
310 case ELOOP:
311 case ENOENT:
312 case ENOTDIR:
313 case EPERM:
314 /* Ignore these errors. They are persistent errors caused
315 by file system contents. */
316 break;
317 default:
318 /* Other errors refer to resource allocation problems and
319 need to be handled by the application. */
320 return false;
321 }
322 else
323 /* No other threads have access to fp. */
324 __fsetlocking (fp, FSETLOCKING_BYCALLER);
325
326 bool ok = true;
327 if (fp != NULL)
328 ok = nss_database_reload_1 (staging, fp);
329
330 /* Apply defaults. */
331 if (ok)
332 {
333 struct nss_database_default_cache cache = { };
334 for (int i = 0; i < NSS_DATABASE_COUNT; ++i)
335 if (staging->services[i] == NULL)
336 {
337 ok = nss_database_select_default (&cache, i,
338 &staging->services[i]);
339 if (!ok)
340 break;
341 }
342 }
343
344 if (ok)
345 ok = __file_change_detection_for_fp (&staging->nsswitch_conf, fp);
346
347 if (fp != NULL)
348 {
349 int saved_errno = errno;
350 fclose (fp);
351 __set_errno (saved_errno);
352 }
353
354 if (ok && !__file_is_unchanged (&staging->nsswitch_conf, initial))
355 /* Reload is required because the file changed while reading. */
356 staging->nsswitch_conf.size = -1;
357
358 return ok;
359}
360
361static bool
362nss_database_check_reload_and_get (struct nss_database_state *local,
363 nss_action_list *result,
364 enum nss_database database_index)
365{
366 struct stat64 str;
367
368 /* Acquire MO is needed because the thread that sets reload_disabled
369 may have loaded the configuration first, so synchronize with the
370 Release MO store there. */
371 if (atomic_load_acquire (&local->data.reload_disabled))
372 {
373 *result = local->data.services[database_index];
374 /* No reload, so there is no error. */
375 return true;
376 }
377
378 struct file_change_detection initial;
379 if (!__file_change_detection_for_path (&initial, _PATH_NSSWITCH_CONF))
380 return false;
381
382 __libc_lock_lock (local->lock);
383 if (__file_is_unchanged (&initial, &local->data.nsswitch_conf))
384 {
385 /* Configuration is up-to-date. Read it and return it to the
386 caller. */
387 *result = local->data.services[database_index];
388 __libc_lock_unlock (local->lock);
389 return true;
390 }
391
392 /* Before we reload, verify that "/" hasn't changed. We assume that
393 errors here are very unlikely, but the chance that we're entering
394 a container is also very unlikely, so we err on the side of both
395 very unlikely things not happening at the same time. */
396 if (__stat64 ("/", &str) != 0
397 || (local->root_ino != 0
398 && (str.st_ino != local->root_ino
399 || str.st_dev != local->root_dev)))
400 {
401 /* Change detected; disable reloading. */
402 atomic_store_release (&local->data.reload_disabled, 1);
403 __libc_lock_unlock (local->lock);
404 __nss_module_disable_loading ();
405 return true;
406 }
407 local->root_ino = str.st_ino;
408 local->root_dev = str.st_dev;
409 __libc_lock_unlock (local->lock);
410
411 /* Avoid overwriting the global configuration until we have loaded
412 everything successfully. Otherwise, if the file change
413 information changes back to what is in the global configuration,
414 the lookups would use the partially-written configuration. */
415 struct nss_database_data staging = { .initialized = true, };
416
417 bool ok = nss_database_reload (&staging, &initial);
418
419 if (ok)
420 {
421 __libc_lock_lock (local->lock);
422
423 /* See above for memory order. */
424 if (!atomic_load_acquire (&local->data.reload_disabled))
425 /* This may go back in time if another thread beats this
426 thread with the update, but in this case, a reload happens
427 on the next NSS call. */
428 local->data = staging;
429
430 *result = local->data.services[database_index];
431 __libc_lock_unlock (local->lock);
432 }
433
434 return ok;
435}
436
437bool
438__nss_database_get (enum nss_database db, nss_action_list *actions)
439{
440 struct nss_database_state *local = nss_database_state_get ();
441 return nss_database_check_reload_and_get (local, actions, db);
442}
443
444nss_action_list
445__nss_database_get_noreload (enum nss_database db)
446{
447 /* There must have been a previous __nss_database_get call. */
448 struct nss_database_state *local = atomic_load_acquire (&global_database_state);
449 assert (local != NULL);
450
451 __libc_lock_lock (local->lock);
452 nss_action_list result = local->data.services[db];
453 __libc_lock_unlock (local->lock);
454 return result;
455}
456
457void __libc_freeres_fn_section
458__nss_database_freeres (void)
459{
460 free (global_database_state);
461 global_database_state = NULL;
462}
463
464void
465__nss_database_fork_prepare_parent (struct nss_database_data *data)
466{
467 /* Do not use allocate_once to trigger loading unnecessarily. */
468 struct nss_database_state *local = atomic_load_acquire (&global_database_state);
469 if (local == NULL)
470 data->initialized = false;
471 else
472 {
473 /* Make a copy of the configuration. This approach was chosen
474 because it avoids acquiring the lock during the actual
475 fork. */
476 __libc_lock_lock (local->lock);
477 *data = local->data;
478 __libc_lock_unlock (local->lock);
479 }
480}
481
482void
483__nss_database_fork_subprocess (struct nss_database_data *data)
484{
485 struct nss_database_state *local = atomic_load_acquire (&global_database_state);
486 if (data->initialized)
487 {
488 /* Restore the state at the point of the fork. */
489 assert (local != NULL);
490 local->data = *data;
491 __libc_lock_init (local->lock);
492 }
493 else if (local != NULL)
494 /* The NSS configuration was loaded concurrently during fork. We
495 do not know its state, so we need to discard it. */
496 global_database_state = NULL;
497}
498