]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/dynamic-user.c
cgroup-util: add mask definitions for sets of controllers supported by cgroupsv1...
[thirdparty/systemd.git] / src / core / dynamic-user.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
29206d46
LP
2
3#include <grp.h>
4#include <pwd.h>
5#include <sys/file.h>
6
98e4fcec 7#include "clean-ipc.h"
29206d46
LP
8#include "dynamic-user.h"
9#include "fd-util.h"
e6a7ec4b 10#include "fileio.h"
29206d46 11#include "fs-util.h"
e6a7ec4b 12#include "io-util.h"
29206d46
LP
13#include "parse-util.h"
14#include "random-util.h"
d68c645b 15#include "serialize.h"
57b7a260 16#include "socket-util.h"
29206d46
LP
17#include "stdio-util.h"
18#include "string-util.h"
19#include "user-util.h"
29206d46 20
29206d46 21/* Takes a value generated randomly or by hashing and turns it into a UID in the right range */
61755fda 22#define UID_CLAMP_INTO_RANGE(rnd) (((uid_t) (rnd) % (DYNAMIC_UID_MAX - DYNAMIC_UID_MIN + 1)) + DYNAMIC_UID_MIN)
29206d46 23
8301aa0b
YW
24DEFINE_PRIVATE_TRIVIAL_REF_FUNC(DynamicUser, dynamic_user);
25
29206d46
LP
26static DynamicUser* dynamic_user_free(DynamicUser *d) {
27 if (!d)
28 return NULL;
29
30 if (d->manager)
31 (void) hashmap_remove(d->manager->dynamic_users, d->name);
32
33 safe_close_pair(d->storage_socket);
6b430fdb 34 return mfree(d);
29206d46
LP
35}
36
37static int dynamic_user_add(Manager *m, const char *name, int storage_socket[2], DynamicUser **ret) {
33430217 38 DynamicUser *d;
29206d46
LP
39 int r;
40
41 assert(m);
42 assert(name);
43 assert(storage_socket);
44
45 r = hashmap_ensure_allocated(&m->dynamic_users, &string_hash_ops);
46 if (r < 0)
47 return r;
48
49 d = malloc0(offsetof(DynamicUser, name) + strlen(name) + 1);
50 if (!d)
51 return -ENOMEM;
52
53 strcpy(d->name, name);
54
55 d->storage_socket[0] = storage_socket[0];
56 d->storage_socket[1] = storage_socket[1];
57
58 r = hashmap_put(m->dynamic_users, d->name, d);
59 if (r < 0) {
60 free(d);
61 return r;
62 }
63
64 d->manager = m;
65
66 if (ret)
67 *ret = d;
68
69 return 0;
70}
71
9da440b1 72static int dynamic_user_acquire(Manager *m, const char *name, DynamicUser** ret) {
29206d46
LP
73 _cleanup_close_pair_ int storage_socket[2] = { -1, -1 };
74 DynamicUser *d;
75 int r;
76
77 assert(m);
78 assert(name);
79
80 /* Return the DynamicUser structure for a specific user name. Note that this won't actually allocate a UID for
81 * it, but just prepare the data structure for it. The UID is allocated only on demand, when it's really
82 * needed, and in the child process we fork off, since allocation involves NSS checks which are not OK to do
83 * from PID 1. To allow the children and PID 1 share information about allocated UIDs we use an anonymous
84 * AF_UNIX/SOCK_DGRAM socket (called the "storage socket") that contains at most one datagram with the
85 * allocated UID number, plus an fd referencing the lock file for the UID
86 * (i.e. /run/systemd/dynamic-uid/$UID). Why involve the socket pair? So that PID 1 and all its children can
87 * share the same storage for the UID and lock fd, simply by inheriting the storage socket fds. The socket pair
88 * may exist in three different states:
89 *
90 * a) no datagram stored. This is the initial state. In this case the dynamic user was never realized.
91 *
92 * b) a datagram containing a UID stored, but no lock fd attached to it. In this case there was already a
93 * statically assigned UID by the same name, which we are reusing.
94 *
95 * c) a datagram containing a UID stored, and a lock fd is attached to it. In this case we allocated a dynamic
96 * UID and locked it in the file system, using the lock fd.
97 *
98 * As PID 1 and various children might access the socket pair simultaneously, and pop the datagram or push it
99 * back in any time, we also maintain a lock on the socket pair. Note one peculiarity regarding locking here:
100 * the UID lock on disk is protected via a BSD file lock (i.e. an fd-bound lock), so that the lock is kept in
101 * place as long as there's a reference to the fd open. The lock on the storage socket pair however is a POSIX
102 * file lock (i.e. a process-bound lock), as all users share the same fd of this (after all it is anonymous,
103 * nobody else could get any access to it except via our own fd) and we want to synchronize access between all
104 * processes that have access to it. */
105
106 d = hashmap_get(m->dynamic_users, name);
107 if (d) {
288ca7af
YW
108 if (ret) {
109 /* We already have a structure for the dynamic user, let's increase the ref count and reuse it */
110 d->n_ref++;
111 *ret = d;
112 }
29206d46
LP
113 return 0;
114 }
115
116 if (!valid_user_group_name_or_id(name))
117 return -EINVAL;
118
119 if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, storage_socket) < 0)
120 return -errno;
121
122 r = dynamic_user_add(m, name, storage_socket, &d);
123 if (r < 0)
124 return r;
125
126 storage_socket[0] = storage_socket[1] = -1;
127
128 if (ret) {
129 d->n_ref++;
130 *ret = d;
131 }
132
133 return 1;
134}
135
fd63e712
LP
136static int make_uid_symlinks(uid_t uid, const char *name, bool b) {
137
fbd0b64f 138 char path1[STRLEN("/run/systemd/dynamic-uid/direct:") + DECIMAL_STR_MAX(uid_t) + 1];
fd63e712 139 const char *path2;
986a34a6 140 int r = 0, k;
fd63e712
LP
141
142 /* Add direct additional symlinks for direct lookups of dynamic UIDs and their names by userspace code. The
143 * only reason we have this is because dbus-daemon cannot use D-Bus for resolving users and groups (since it
144 * would be its own client then). We hence keep these world-readable symlinks in place, so that the
145 * unprivileged dbus user can read the mappings when it needs them via these symlinks instead of having to go
146 * via the bus. Ideally, we'd use the lock files we keep for this anyway, but we can't since we use BSD locks
147 * on them and as those may be taken by any user with read access we can't make them world-readable. */
148
149 xsprintf(path1, "/run/systemd/dynamic-uid/direct:" UID_FMT, uid);
986a34a6
ZJS
150 if (unlink(path1) < 0 && errno != ENOENT)
151 r = -errno;
152
153 if (b && symlink(name, path1) < 0) {
154 k = log_warning_errno(errno, "Failed to symlink \"%s\": %m", path1);
155 if (r == 0)
156 r = k;
fd63e712
LP
157 }
158
159 path2 = strjoina("/run/systemd/dynamic-uid/direct:", name);
986a34a6
ZJS
160 if (unlink(path2) < 0 && errno != ENOENT) {
161 k = -errno;
162 if (r == 0)
163 r = k;
fd63e712 164 }
986a34a6 165
fbd0b64f 166 if (b && symlink(path1 + STRLEN("/run/systemd/dynamic-uid/direct:"), path2) < 0) {
986a34a6
ZJS
167 k = log_warning_errno(errno, "Failed to symlink \"%s\": %m", path2);
168 if (r == 0)
169 r = k;
fd63e712
LP
170 }
171
172 return r;
173}
174
da50b85a
LP
175static int pick_uid(char **suggested_paths, const char *name, uid_t *ret_uid) {
176
177 /* Find a suitable free UID. We use the following strategy to find a suitable UID:
178 *
179 * 1. Initially, we try to read the UID of a number of specified paths. If any of these UIDs works, we use
180 * them. We use in order to increase the chance of UID reuse, if StateDirectory=, CacheDirectory= or
181 * LogDirectory= are used, as reusing the UID these directories are owned by saves us from having to
182 * recursively chown() them to new users.
183 *
184 * 2. If that didn't yield a currently unused UID, we hash the user name, and try to use that. This should be
185 * pretty good, as the use ris by default derived from the unit name, and hence the same service and same
186 * user should usually get the same UID as long as our hashing doesn't clash.
187 *
188 * 3. Finally, if that didn't work, we randomly pick UIDs, until we find one that is empty.
189 *
190 * Since the dynamic UID space is relatively small we'll stop trying after 100 iterations, giving up. */
191
192 enum {
193 PHASE_SUGGESTED, /* the first phase, reusing directory ownership UIDs */
194 PHASE_HASHED, /* the second phase, deriving a UID from the username by hashing */
195 PHASE_RANDOM, /* the last phase, randomly picking UIDs */
196 } phase = PHASE_SUGGESTED;
29206d46
LP
197
198 static const uint8_t hash_key[] = {
199 0x37, 0x53, 0x7e, 0x31, 0xcf, 0xce, 0x48, 0xf5,
200 0x8a, 0xbb, 0x39, 0x57, 0x8d, 0xd9, 0xec, 0x59
201 };
202
da50b85a 203 unsigned n_tries = 100, current_suggested = 0;
29206d46
LP
204 int r;
205
29206d46
LP
206 (void) mkdir("/run/systemd/dynamic-uid", 0755);
207
208 for (;;) {
fbd0b64f 209 char lock_path[STRLEN("/run/systemd/dynamic-uid/") + DECIMAL_STR_MAX(uid_t) + 1];
29206d46 210 _cleanup_close_ int lock_fd = -1;
da50b85a 211 uid_t candidate;
29206d46
LP
212 ssize_t l;
213
214 if (--n_tries <= 0) /* Give up retrying eventually */
215 return -EBUSY;
216
da50b85a
LP
217 switch (phase) {
218
219 case PHASE_SUGGESTED: {
220 struct stat st;
221
222 if (!suggested_paths || !suggested_paths[current_suggested]) {
223 /* We reached the end of the suggested paths list, let's try by hashing the name */
224 phase = PHASE_HASHED;
225 continue;
226 }
227
228 if (stat(suggested_paths[current_suggested++], &st) < 0)
229 continue; /* We can't read the UID of this path, but that doesn't matter, just try the next */
230
231 candidate = st.st_uid;
232 break;
233 }
234
235 case PHASE_HASHED:
236 /* A static user by this name does not exist yet. Let's find a free ID then, and use that. We
237 * start with a UID generated as hash from the user name. */
238 candidate = UID_CLAMP_INTO_RANGE(siphash24(name, strlen(name), hash_key));
239
240 /* If this one fails, we should proceed with random tries */
241 phase = PHASE_RANDOM;
242 break;
243
244 case PHASE_RANDOM:
245
246 /* Pick another random UID, and see if that works for us. */
247 random_bytes(&candidate, sizeof(candidate));
248 candidate = UID_CLAMP_INTO_RANGE(candidate);
249 break;
250
251 default:
252 assert_not_reached("unknown phase");
253 }
254
255 /* Make sure whatever we picked here actually is in the right range */
61755fda 256 if (!uid_is_dynamic(candidate))
da50b85a 257 continue;
29206d46
LP
258
259 xsprintf(lock_path, "/run/systemd/dynamic-uid/" UID_FMT, candidate);
260
261 for (;;) {
262 struct stat st;
263
264 lock_fd = open(lock_path, O_CREAT|O_RDWR|O_NOFOLLOW|O_CLOEXEC|O_NOCTTY, 0600);
265 if (lock_fd < 0)
266 return -errno;
267
268 r = flock(lock_fd, LOCK_EX|LOCK_NB); /* Try to get a BSD file lock on the UID lock file */
269 if (r < 0) {
3742095b 270 if (IN_SET(errno, EBUSY, EAGAIN))
29206d46
LP
271 goto next; /* already in use */
272
273 return -errno;
274 }
275
276 if (fstat(lock_fd, &st) < 0)
277 return -errno;
278 if (st.st_nlink > 0)
279 break;
280
629ff674 281 /* Oh, bummer, we got the lock, but the file was unlinked between the time we opened it and
29206d46
LP
282 * got the lock. Close it, and try again. */
283 lock_fd = safe_close(lock_fd);
284 }
285
286 /* Some superficial check whether this UID/GID might already be taken by some static user */
98e4fcec
LP
287 if (getpwuid(candidate) ||
288 getgrgid((gid_t) candidate) ||
289 search_ipc(candidate, (gid_t) candidate) != 0) {
29206d46 290 (void) unlink(lock_path);
da50b85a 291 continue;
29206d46
LP
292 }
293
294 /* Let's store the user name in the lock file, so that we can use it for looking up the username for a UID */
295 l = pwritev(lock_fd,
296 (struct iovec[2]) {
e6a7ec4b
LP
297 IOVEC_INIT_STRING(name),
298 IOVEC_INIT((char[1]) { '\n' }, 1),
29206d46
LP
299 }, 2, 0);
300 if (l < 0) {
e53c42ca 301 r = -errno;
29206d46 302 (void) unlink(lock_path);
e53c42ca 303 return r;
29206d46
LP
304 }
305
306 (void) ftruncate(lock_fd, l);
fd63e712 307 (void) make_uid_symlinks(candidate, name, true); /* also add direct lookup symlinks */
29206d46
LP
308
309 *ret_uid = candidate;
c10d6bdb 310 return TAKE_FD(lock_fd);
29206d46
LP
311
312 next:
da50b85a 313 ;
29206d46
LP
314 }
315}
316
317static int dynamic_user_pop(DynamicUser *d, uid_t *ret_uid, int *ret_lock_fd) {
318 uid_t uid = UID_INVALID;
e6a7ec4b 319 struct iovec iov = IOVEC_INIT(&uid, sizeof(uid));
d34673ec 320 int lock_fd;
29206d46 321 ssize_t k;
29206d46
LP
322
323 assert(d);
324 assert(ret_uid);
325 assert(ret_lock_fd);
326
327 /* Read the UID and lock fd that is stored in the storage AF_UNIX socket. This should be called with the lock
328 * on the socket taken. */
329
d34673ec 330 k = receive_one_fd_iov(d->storage_socket[0], &iov, 1, MSG_DONTWAIT, &lock_fd);
29206d46 331 if (k < 0)
d34673ec 332 return (int) k;
29206d46
LP
333
334 *ret_uid = uid;
335 *ret_lock_fd = lock_fd;
336
337 return 0;
338}
339
340static int dynamic_user_push(DynamicUser *d, uid_t uid, int lock_fd) {
e6a7ec4b 341 struct iovec iov = IOVEC_INIT(&uid, sizeof(uid));
29206d46
LP
342
343 assert(d);
344
345 /* Store the UID and lock_fd in the storage socket. This should be called with the socket pair lock taken. */
d34673ec 346 return send_one_fd_iov(d->storage_socket[1], lock_fd, &iov, 1, MSG_DONTWAIT);
29206d46
LP
347}
348
fd63e712 349static void unlink_uid_lock(int lock_fd, uid_t uid, const char *name) {
fbd0b64f 350 char lock_path[STRLEN("/run/systemd/dynamic-uid/") + DECIMAL_STR_MAX(uid_t) + 1];
29206d46
LP
351
352 if (lock_fd < 0)
353 return;
354
355 xsprintf(lock_path, "/run/systemd/dynamic-uid/" UID_FMT, uid);
fd63e712
LP
356 (void) unlink(lock_path);
357
358 (void) make_uid_symlinks(uid, name, false); /* remove direct lookup symlinks */
29206d46
LP
359}
360
362d90b7
ZJS
361static int lockfp(int fd, int *fd_lock) {
362 if (lockf(fd, F_LOCK, 0) < 0)
363 return -errno;
364 *fd_lock = fd;
365 return 0;
366}
367
368static void unlockfp(int *fd_lock) {
369 if (*fd_lock < 0)
370 return;
371 lockf(*fd_lock, F_ULOCK, 0);
372 *fd_lock = -1;
373}
374
c2983a7f
ZJS
375static int dynamic_user_realize(
376 DynamicUser *d,
377 char **suggested_dirs,
378 uid_t *ret_uid, gid_t *ret_gid,
379 bool is_user) {
29206d46 380
362d90b7
ZJS
381 _cleanup_(unlockfp) int storage_socket0_lock = -1;
382 _cleanup_close_ int uid_lock_fd = -1;
383 _cleanup_close_ int etc_passwd_lock_fd = -1;
c2983a7f
ZJS
384 uid_t num = UID_INVALID; /* a uid if is_user, and a gid otherwise */
385 gid_t gid = GID_INVALID; /* a gid if is_user, ignored otherwise */
29206d46
LP
386 int r;
387
388 assert(d);
c2983a7f
ZJS
389 assert(is_user == !!ret_uid);
390 assert(ret_gid);
29206d46
LP
391
392 /* Acquire a UID for the user name. This will allocate a UID for the user name if the user doesn't exist
393 * yet. If it already exists its existing UID/GID will be reused. */
394
362d90b7
ZJS
395 r = lockfp(d->storage_socket[0], &storage_socket0_lock);
396 if (r < 0)
397 return r;
29206d46 398
c2983a7f 399 r = dynamic_user_pop(d, &num, &uid_lock_fd);
29206d46
LP
400 if (r < 0) {
401 int new_uid_lock_fd;
402 uid_t new_uid;
403
404 if (r != -EAGAIN)
362d90b7 405 return r;
29206d46
LP
406
407 /* OK, nothing stored yet, let's try to find something useful. While we are working on this release the
408 * lock however, so that nobody else blocks on our NSS lookups. */
362d90b7 409 unlockfp(&storage_socket0_lock);
29206d46
LP
410
411 /* Let's see if a proper, static user or group by this name exists. Try to take the lock on
412 * /etc/passwd, if that fails with EROFS then /etc is read-only. In that case it's fine if we don't
413 * take the lock, given that users can't be added there anyway in this case. */
414 etc_passwd_lock_fd = take_etc_passwd_lock(NULL);
415 if (etc_passwd_lock_fd < 0 && etc_passwd_lock_fd != -EROFS)
416 return etc_passwd_lock_fd;
417
418 /* First, let's parse this as numeric UID */
c2983a7f 419 r = parse_uid(d->name, &num);
29206d46
LP
420 if (r < 0) {
421 struct passwd *p;
422 struct group *g;
423
9ec655cb
YW
424 if (is_user) {
425 /* OK, this is not a numeric UID. Let's see if there's a user by this name */
426 p = getpwnam(d->name);
c2983a7f
ZJS
427 if (p) {
428 num = p->pw_uid;
429 gid = p->pw_gid;
430 } else {
9ec655cb
YW
431 /* if the user does not exist but the group with the same name exists, refuse operation */
432 g = getgrnam(d->name);
433 if (g)
434 return -EILSEQ;
435 }
436 } else {
437 /* Let's see if there's a group by this name */
438 g = getgrnam(d->name);
439 if (g)
c2983a7f 440 num = (uid_t) g->gr_gid;
9ec655cb
YW
441 else {
442 /* if the group does not exist but the user with the same name exists, refuse operation */
443 p = getpwnam(d->name);
444 if (p)
445 return -EILSEQ;
446 }
29206d46
LP
447 }
448 }
449
c2983a7f 450 if (num == UID_INVALID) {
29206d46
LP
451 /* No static UID assigned yet, excellent. Let's pick a new dynamic one, and lock it. */
452
c2983a7f 453 uid_lock_fd = pick_uid(suggested_dirs, d->name, &num);
29206d46
LP
454 if (uid_lock_fd < 0)
455 return uid_lock_fd;
456 }
457
458 /* So, we found a working UID/lock combination. Let's see if we actually still need it. */
362d90b7
ZJS
459 r = lockfp(d->storage_socket[0], &storage_socket0_lock);
460 if (r < 0) {
c2983a7f 461 unlink_uid_lock(uid_lock_fd, num, d->name);
362d90b7 462 return r;
29206d46
LP
463 }
464
465 r = dynamic_user_pop(d, &new_uid, &new_uid_lock_fd);
466 if (r < 0) {
467 if (r != -EAGAIN) {
468 /* OK, something bad happened, let's get rid of the bits we acquired. */
c2983a7f 469 unlink_uid_lock(uid_lock_fd, num, d->name);
362d90b7 470 return r;
29206d46
LP
471 }
472
473 /* Great! Nothing is stored here, still. Store our newly acquired data. */
474 } else {
475 /* Hmm, so as it appears there's now something stored in the storage socket. Throw away what we
476 * acquired, and use what's stored now. */
477
c2983a7f 478 unlink_uid_lock(uid_lock_fd, num, d->name);
29206d46
LP
479 safe_close(uid_lock_fd);
480
c2983a7f 481 num = new_uid;
29206d46
LP
482 uid_lock_fd = new_uid_lock_fd;
483 }
25a1df7c
YW
484 } else if (is_user && !uid_is_dynamic(num)) {
485 struct passwd *p;
486
487 /* Statically allocated user may have different uid and gid. So, let's obtain the gid. */
488 errno = 0;
489 p = getpwuid(num);
490 if (!p)
491 return errno > 0 ? -errno : -ESRCH;
492
493 gid = p->pw_gid;
29206d46
LP
494 }
495
496 /* If the UID/GID was already allocated dynamically, push the data we popped out back in. If it was already
497 * allocated statically, push the UID back too, but do not push the lock fd in. If we allocated the UID
498 * dynamically right here, push that in along with the lock fd for it. */
c2983a7f 499 r = dynamic_user_push(d, num, uid_lock_fd);
29206d46 500 if (r < 0)
362d90b7 501 return r;
29206d46 502
c2983a7f
ZJS
503 if (is_user) {
504 *ret_uid = num;
505 *ret_gid = gid != GID_INVALID ? gid : num;
506 } else
507 *ret_gid = num;
508
362d90b7 509 return 0;
29206d46
LP
510}
511
f9bfa696 512int dynamic_user_current(DynamicUser *d, uid_t *ret) {
362d90b7 513 _cleanup_(unlockfp) int storage_socket0_lock = -1;
29206d46
LP
514 _cleanup_close_ int lock_fd = -1;
515 uid_t uid;
516 int r;
517
518 assert(d);
519 assert(ret);
520
521 /* Get the currently assigned UID for the user, if there's any. This simply pops the data from the storage socket, and pushes it back in right-away. */
522
362d90b7
ZJS
523 r = lockfp(d->storage_socket[0], &storage_socket0_lock);
524 if (r < 0)
525 return r;
29206d46
LP
526
527 r = dynamic_user_pop(d, &uid, &lock_fd);
528 if (r < 0)
362d90b7 529 return r;
29206d46
LP
530
531 r = dynamic_user_push(d, uid, lock_fd);
532 if (r < 0)
362d90b7 533 return r;
29206d46
LP
534
535 *ret = uid;
362d90b7 536 return 0;
29206d46
LP
537}
538
9da440b1 539static DynamicUser* dynamic_user_unref(DynamicUser *d) {
29206d46
LP
540 if (!d)
541 return NULL;
542
543 /* Note that this doesn't actually release any resources itself. If a dynamic user should be fully destroyed
544 * and its UID released, use dynamic_user_destroy() instead. NB: the dynamic user table may contain entries
545 * with no references, which is commonly the case right before a daemon reload. */
546
547 assert(d->n_ref > 0);
548 d->n_ref--;
549
550 return NULL;
551}
552
553static int dynamic_user_close(DynamicUser *d) {
362d90b7 554 _cleanup_(unlockfp) int storage_socket0_lock = -1;
29206d46
LP
555 _cleanup_close_ int lock_fd = -1;
556 uid_t uid;
557 int r;
558
559 /* Release the user ID, by releasing the lock on it, and emptying the storage socket. After this the user is
560 * unrealized again, much like it was after it the DynamicUser object was first allocated. */
561
362d90b7
ZJS
562 r = lockfp(d->storage_socket[0], &storage_socket0_lock);
563 if (r < 0)
564 return r;
29206d46
LP
565
566 r = dynamic_user_pop(d, &uid, &lock_fd);
362d90b7 567 if (r == -EAGAIN)
29206d46 568 /* User wasn't realized yet, nothing to do. */
362d90b7 569 return 0;
29206d46 570 if (r < 0)
362d90b7 571 return r;
29206d46
LP
572
573 /* This dynamic user was realized and dynamically allocated. In this case, let's remove the lock file. */
fd63e712 574 unlink_uid_lock(lock_fd, uid, d->name);
362d90b7 575 return 1;
29206d46
LP
576}
577
9da440b1 578static DynamicUser* dynamic_user_destroy(DynamicUser *d) {
29206d46
LP
579 if (!d)
580 return NULL;
581
582 /* Drop a reference to a DynamicUser object, and destroy the user completely if this was the last
583 * reference. This is called whenever a service is shut down and wants its dynamic UID gone. Note that
584 * dynamic_user_unref() is what is called whenever a service is simply freed, for example during a reload
585 * cycle, where the dynamic users should not be destroyed, but our datastructures should. */
586
587 dynamic_user_unref(d);
588
589 if (d->n_ref > 0)
590 return NULL;
591
592 (void) dynamic_user_close(d);
593 return dynamic_user_free(d);
594}
595
596int dynamic_user_serialize(Manager *m, FILE *f, FDSet *fds) {
597 DynamicUser *d;
598 Iterator i;
599
600 assert(m);
601 assert(f);
602 assert(fds);
603
604 /* Dump the dynamic user database into the manager serialization, to deal with daemon reloads. */
605
606 HASHMAP_FOREACH(d, m->dynamic_users, i) {
607 int copy0, copy1;
608
609 copy0 = fdset_put_dup(fds, d->storage_socket[0]);
610 if (copy0 < 0)
d68c645b 611 return log_error_errno(copy0, "Failed to add dynamic user storage fd to serialization: %m");
29206d46
LP
612
613 copy1 = fdset_put_dup(fds, d->storage_socket[1]);
614 if (copy1 < 0)
d68c645b 615 return log_error_errno(copy1, "Failed to add dynamic user storage fd to serialization: %m");
29206d46 616
d68c645b 617 (void) serialize_item_format(f, "dynamic-user", "%s %i %i", d->name, copy0, copy1);
29206d46
LP
618 }
619
620 return 0;
621}
622
623void dynamic_user_deserialize_one(Manager *m, const char *value, FDSet *fds) {
624 _cleanup_free_ char *name = NULL, *s0 = NULL, *s1 = NULL;
625 int r, fd0, fd1;
626
627 assert(m);
628 assert(value);
629 assert(fds);
630
631 /* Parse the serialization again, after a daemon reload */
632
633 r = extract_many_words(&value, NULL, 0, &name, &s0, &s1, NULL);
634 if (r != 3 || !isempty(value)) {
635 log_debug("Unable to parse dynamic user line.");
636 return;
637 }
638
639 if (safe_atoi(s0, &fd0) < 0 || !fdset_contains(fds, fd0)) {
640 log_debug("Unable to process dynamic user fd specification.");
641 return;
642 }
643
644 if (safe_atoi(s1, &fd1) < 0 || !fdset_contains(fds, fd1)) {
645 log_debug("Unable to process dynamic user fd specification.");
646 return;
647 }
648
649 r = dynamic_user_add(m, name, (int[]) { fd0, fd1 }, NULL);
650 if (r < 0) {
651 log_debug_errno(r, "Failed to add dynamic user: %m");
652 return;
653 }
654
655 (void) fdset_remove(fds, fd0);
656 (void) fdset_remove(fds, fd1);
657}
658
659void dynamic_user_vacuum(Manager *m, bool close_user) {
660 DynamicUser *d;
661 Iterator i;
662
663 assert(m);
664
665 /* Empty the dynamic user database, optionally cleaning up orphaned dynamic users, i.e. destroy and free users
666 * to which no reference exist. This is called after a daemon reload finished, in order to destroy users which
667 * might not be referenced anymore. */
668
669 HASHMAP_FOREACH(d, m->dynamic_users, i) {
670 if (d->n_ref > 0)
671 continue;
672
673 if (close_user) {
674 log_debug("Removing orphaned dynamic user %s", d->name);
675 (void) dynamic_user_close(d);
676 }
677
678 dynamic_user_free(d);
679 }
680}
681
682int dynamic_user_lookup_uid(Manager *m, uid_t uid, char **ret) {
fbd0b64f 683 char lock_path[STRLEN("/run/systemd/dynamic-uid/") + DECIMAL_STR_MAX(uid_t) + 1];
29206d46
LP
684 _cleanup_free_ char *user = NULL;
685 uid_t check_uid;
686 int r;
687
688 assert(m);
689 assert(ret);
690
61755fda
ZJS
691 /* A friendly way to translate a dynamic user's UID into a name. */
692 if (!uid_is_dynamic(uid))
29206d46
LP
693 return -ESRCH;
694
695 xsprintf(lock_path, "/run/systemd/dynamic-uid/" UID_FMT, uid);
696 r = read_one_line_file(lock_path, &user);
697 if (r == -ENOENT)
698 return -ESRCH;
699 if (r < 0)
700 return r;
701
702 /* The lock file might be stale, hence let's verify the data before we return it */
703 r = dynamic_user_lookup_name(m, user, &check_uid);
704 if (r < 0)
705 return r;
706 if (check_uid != uid) /* lock file doesn't match our own idea */
707 return -ESRCH;
708
ae2a15bc 709 *ret = TAKE_PTR(user);
29206d46
LP
710
711 return 0;
712}
713
714int dynamic_user_lookup_name(Manager *m, const char *name, uid_t *ret) {
715 DynamicUser *d;
716 int r;
717
718 assert(m);
719 assert(name);
720 assert(ret);
721
722 /* A friendly call for translating a dynamic user's name into its UID */
723
724 d = hashmap_get(m->dynamic_users, name);
725 if (!d)
726 return -ESRCH;
727
728 r = dynamic_user_current(d, ret);
729 if (r == -EAGAIN) /* not realized yet? */
730 return -ESRCH;
731
732 return r;
733}
734
735int dynamic_creds_acquire(DynamicCreds *creds, Manager *m, const char *user, const char *group) {
736 bool acquired = false;
737 int r;
738
739 assert(creds);
740 assert(m);
741
742 /* A DynamicUser object encapsulates an allocation of both a UID and a GID for a specific name. However, some
743 * services use different user and groups. For cases like that there's DynamicCreds containing a pair of user
744 * and group. This call allocates a pair. */
745
746 if (!creds->user && user) {
747 r = dynamic_user_acquire(m, user, &creds->user);
748 if (r < 0)
749 return r;
750
751 acquired = true;
752 }
753
754 if (!creds->group) {
755
756 if (creds->user && (!group || streq_ptr(user, group)))
757 creds->group = dynamic_user_ref(creds->user);
758 else {
759 r = dynamic_user_acquire(m, group, &creds->group);
760 if (r < 0) {
761 if (acquired)
762 creds->user = dynamic_user_unref(creds->user);
763 return r;
764 }
765 }
766 }
767
768 return 0;
769}
770
da50b85a 771int dynamic_creds_realize(DynamicCreds *creds, char **suggested_paths, uid_t *uid, gid_t *gid) {
29206d46
LP
772 uid_t u = UID_INVALID;
773 gid_t g = GID_INVALID;
774 int r;
775
776 assert(creds);
777 assert(uid);
778 assert(gid);
779
780 /* Realize both the referenced user and group */
781
782 if (creds->user) {
c2983a7f 783 r = dynamic_user_realize(creds->user, suggested_paths, &u, &g, true);
29206d46
LP
784 if (r < 0)
785 return r;
786 }
787
788 if (creds->group && creds->group != creds->user) {
c2983a7f 789 r = dynamic_user_realize(creds->group, suggested_paths, NULL, &g, false);
29206d46
LP
790 if (r < 0)
791 return r;
c2983a7f 792 }
29206d46
LP
793
794 *uid = u;
795 *gid = g;
29206d46
LP
796 return 0;
797}
798
799void dynamic_creds_unref(DynamicCreds *creds) {
800 assert(creds);
801
802 creds->user = dynamic_user_unref(creds->user);
803 creds->group = dynamic_user_unref(creds->group);
804}
805
806void dynamic_creds_destroy(DynamicCreds *creds) {
807 assert(creds);
808
809 creds->user = dynamic_user_destroy(creds->user);
810 creds->group = dynamic_user_destroy(creds->group);
811}