]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/dynamic-user.c
2 This file is part of systemd.
4 Copyright 2016 Lennart Poettering
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
24 #include "dynamic-user.h"
29 #include "parse-util.h"
30 #include "random-util.h"
31 #include "stdio-util.h"
32 #include "string-util.h"
33 #include "user-util.h"
35 /* Takes a value generated randomly or by hashing and turns it into a UID in the right range */
36 #define UID_CLAMP_INTO_RANGE(rnd) (((uid_t) (rnd) % (DYNAMIC_UID_MAX - DYNAMIC_UID_MIN + 1)) + DYNAMIC_UID_MIN)
38 static DynamicUser
* dynamic_user_free ( DynamicUser
* d
) {
43 ( void ) hashmap_remove ( d
-> manager
-> dynamic_users
, d
-> name
);
45 safe_close_pair ( d
-> storage_socket
);
49 static int dynamic_user_add ( Manager
* m
, const char * name
, int storage_socket
[ 2 ], DynamicUser
** ret
) {
50 DynamicUser
* d
= NULL
;
55 assert ( storage_socket
);
57 r
= hashmap_ensure_allocated (& m
-> dynamic_users
, & string_hash_ops
);
61 d
= malloc0 ( offsetof ( DynamicUser
, name
) + strlen ( name
) + 1 );
65 strcpy ( d
-> name
, name
);
67 d
-> storage_socket
[ 0 ] = storage_socket
[ 0 ];
68 d
-> storage_socket
[ 1 ] = storage_socket
[ 1 ];
70 r
= hashmap_put ( m
-> dynamic_users
, d
-> name
, d
);
84 int dynamic_user_acquire ( Manager
* m
, const char * name
, DynamicUser
** ret
) {
85 _cleanup_close_pair_
int storage_socket
[ 2 ] = { - 1 , - 1 };
92 /* Return the DynamicUser structure for a specific user name. Note that this won't actually allocate a UID for
93 * it, but just prepare the data structure for it. The UID is allocated only on demand, when it's really
94 * needed, and in the child process we fork off, since allocation involves NSS checks which are not OK to do
95 * from PID 1. To allow the children and PID 1 share information about allocated UIDs we use an anonymous
96 * AF_UNIX/SOCK_DGRAM socket (called the "storage socket") that contains at most one datagram with the
97 * allocated UID number, plus an fd referencing the lock file for the UID
98 * (i.e. /run/systemd/dynamic-uid/$UID). Why involve the socket pair? So that PID 1 and all its children can
99 * share the same storage for the UID and lock fd, simply by inheriting the storage socket fds. The socket pair
100 * may exist in three different states:
102 * a) no datagram stored. This is the initial state. In this case the dynamic user was never realized.
104 * b) a datagram containing a UID stored, but no lock fd attached to it. In this case there was already a
105 * statically assigned UID by the same name, which we are reusing.
107 * c) a datagram containing a UID stored, and a lock fd is attached to it. In this case we allocated a dynamic
108 * UID and locked it in the file system, using the lock fd.
110 * As PID 1 and various children might access the socket pair simultaneously, and pop the datagram or push it
111 * back in any time, we also maintain a lock on the socket pair. Note one peculiarity regarding locking here:
112 * 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
113 * place as long as there's a reference to the fd open. The lock on the storage socket pair however is a POSIX
114 * file lock (i.e. a process-bound lock), as all users share the same fd of this (after all it is anonymous,
115 * nobody else could get any access to it except via our own fd) and we want to synchronize access between all
116 * processes that have access to it. */
118 d
= hashmap_get ( m
-> dynamic_users
, name
);
120 /* We already have a structure for the dynamic user, let's increase the ref count and reuse it */
126 if (! valid_user_group_name_or_id ( name
))
129 if ( socketpair ( AF_UNIX
, SOCK_DGRAM
| SOCK_CLOEXEC
, 0 , storage_socket
) < 0 )
132 r
= dynamic_user_add ( m
, name
, storage_socket
, & d
);
136 storage_socket
[ 0 ] = storage_socket
[ 1 ] = - 1 ;
146 static int make_uid_symlinks ( uid_t uid
, const char * name
, bool b
) {
148 char path1
[ strlen ( "/run/systemd/dynamic-uid/direct:" ) + DECIMAL_STR_MAX ( uid_t
) + 1 ];
152 /* Add direct additional symlinks for direct lookups of dynamic UIDs and their names by userspace code. The
153 * only reason we have this is because dbus-daemon cannot use D-Bus for resolving users and groups (since it
154 * would be its own client then). We hence keep these world-readable symlinks in place, so that the
155 * unprivileged dbus user can read the mappings when it needs them via these symlinks instead of having to go
156 * via the bus. Ideally, we'd use the lock files we keep for this anyway, but we can't since we use BSD locks
157 * on them and as those may be taken by any user with read access we can't make them world-readable. */
159 xsprintf ( path1
, "/run/systemd/dynamic-uid/direct:" UID_FMT
, uid
);
160 if ( unlink ( path1
) < 0 && errno
!= ENOENT
)
163 if ( b
&& symlink ( name
, path1
) < 0 ) {
164 k
= log_warning_errno ( errno
, "Failed to symlink \" %s \" : %m" , path1
);
169 path2
= strjoina ( "/run/systemd/dynamic-uid/direct:" , name
);
170 if ( unlink ( path2
) < 0 && errno
!= ENOENT
) {
176 if ( b
&& symlink ( path1
+ strlen ( "/run/systemd/dynamic-uid/direct:" ), path2
) < 0 ) {
177 k
= log_warning_errno ( errno
, "Failed to symlink \" %s \" : %m" , path2
);
185 static int pick_uid ( const char * name
, uid_t
* ret_uid
) {
187 static const uint8_t hash_key
[] = {
188 0x37 , 0x53 , 0x7e , 0x31 , 0xcf , 0xce , 0x48 , 0xf5 ,
189 0x8a , 0xbb , 0x39 , 0x57 , 0x8d , 0xd9 , 0xec , 0x59
192 unsigned n_tries
= 100 ;
196 /* A static user by this name does not exist yet. Let's find a free ID then, and use that. We start with a UID
197 * generated as hash from the user name. */
198 candidate
= UID_CLAMP_INTO_RANGE ( siphash24 ( name
, strlen ( name
), hash_key
));
200 ( void ) mkdir ( "/run/systemd/dynamic-uid" , 0755 );
203 char lock_path
[ strlen ( "/run/systemd/dynamic-uid/" ) + DECIMAL_STR_MAX ( uid_t
) + 1 ];
204 _cleanup_close_
int lock_fd
= - 1 ;
207 if (-- n_tries
<= 0 ) /* Give up retrying eventually */
210 if (! uid_is_dynamic ( candidate
))
213 xsprintf ( lock_path
, "/run/systemd/dynamic-uid/" UID_FMT
, candidate
);
218 lock_fd
= open ( lock_path
, O_CREAT
| O_RDWR
| O_NOFOLLOW
| O_CLOEXEC
| O_NOCTTY
, 0600 );
222 r
= flock ( lock_fd
, LOCK_EX
| LOCK_NB
); /* Try to get a BSD file lock on the UID lock file */
224 if ( errno
== EBUSY
|| errno
== EAGAIN
)
225 goto next
; /* already in use */
230 if ( fstat ( lock_fd
, & st
) < 0 )
235 /* Oh, bummer, we got the lock, but the file was unlinked between the time we opened it and
236 * got the lock. Close it, and try again. */
237 lock_fd
= safe_close ( lock_fd
);
240 /* Some superficial check whether this UID/GID might already be taken by some static user */
241 if ( getpwuid ( candidate
) || getgrgid (( gid_t
) candidate
)) {
242 ( void ) unlink ( lock_path
);
246 /* Let's store the user name in the lock file, so that we can use it for looking up the username for a UID */
249 IOVEC_INIT_STRING ( name
),
250 IOVEC_INIT (( char [ 1 ]) { ' \n ' }, 1 ),
253 ( void ) unlink ( lock_path
);
257 ( void ) ftruncate ( lock_fd
, l
);
258 ( void ) make_uid_symlinks ( candidate
, name
, true ); /* also add direct lookup symlinks */
260 * ret_uid
= candidate
;
267 /* Pick another random UID, and see if that works for us. */
268 random_bytes (& candidate
, sizeof ( candidate
));
269 candidate
= UID_CLAMP_INTO_RANGE ( candidate
);
273 static int dynamic_user_pop ( DynamicUser
* d
, uid_t
* ret_uid
, int * ret_lock_fd
) {
274 uid_t uid
= UID_INVALID
;
275 struct iovec iov
= IOVEC_INIT (& uid
, sizeof ( uid
));
277 struct cmsghdr cmsghdr
;
278 uint8_t buf
[ CMSG_SPACE ( sizeof ( int ))];
281 . msg_control
= & control
,
282 . msg_controllen
= sizeof ( control
),
286 struct cmsghdr
* cmsg
;
295 /* Read the UID and lock fd that is stored in the storage AF_UNIX socket. This should be called with the lock
296 * on the socket taken. */
298 k
= recvmsg ( d
-> storage_socket
[ 0 ], & mh
, MSG_DONTWAIT
| MSG_NOSIGNAL
| MSG_CMSG_CLOEXEC
);
302 cmsg
= cmsg_find (& mh
, SOL_SOCKET
, SCM_RIGHTS
, CMSG_LEN ( sizeof ( int )));
304 lock_fd
= *( int *) CMSG_DATA ( cmsg
);
306 cmsg_close_all (& mh
); /* just in case... */
309 * ret_lock_fd
= lock_fd
;
314 static int dynamic_user_push ( DynamicUser
* d
, uid_t uid
, int lock_fd
) {
315 struct iovec iov
= IOVEC_INIT (& uid
, sizeof ( uid
));
317 struct cmsghdr cmsghdr
;
318 uint8_t buf
[ CMSG_SPACE ( sizeof ( int ))];
321 . msg_control
= & control
,
322 . msg_controllen
= sizeof ( control
),
330 /* Store the UID and lock_fd in the storage socket. This should be called with the socket pair lock taken. */
333 struct cmsghdr
* cmsg
;
335 cmsg
= CMSG_FIRSTHDR (& mh
);
336 cmsg
-> cmsg_level
= SOL_SOCKET
;
337 cmsg
-> cmsg_type
= SCM_RIGHTS
;
338 cmsg
-> cmsg_len
= CMSG_LEN ( sizeof ( int ));
339 memcpy ( CMSG_DATA ( cmsg
), & lock_fd
, sizeof ( int ));
341 mh
. msg_controllen
= CMSG_SPACE ( sizeof ( int ));
343 mh
. msg_control
= NULL
;
344 mh
. msg_controllen
= 0 ;
347 k
= sendmsg ( d
-> storage_socket
[ 1 ], & mh
, MSG_DONTWAIT
| MSG_NOSIGNAL
);
354 static void unlink_uid_lock ( int lock_fd
, uid_t uid
, const char * name
) {
355 char lock_path
[ strlen ( "/run/systemd/dynamic-uid/" ) + DECIMAL_STR_MAX ( uid_t
) + 1 ];
360 xsprintf ( lock_path
, "/run/systemd/dynamic-uid/" UID_FMT
, uid
);
361 ( void ) unlink ( lock_path
);
363 ( void ) make_uid_symlinks ( uid
, name
, false ); /* remove direct lookup symlinks */
366 int dynamic_user_realize ( DynamicUser
* d
, uid_t
* ret
) {
368 _cleanup_close_
int etc_passwd_lock_fd
= - 1 , uid_lock_fd
= - 1 ;
369 uid_t uid
= UID_INVALID
;
374 /* Acquire a UID for the user name. This will allocate a UID for the user name if the user doesn't exist
375 * yet. If it already exists its existing UID/GID will be reused. */
377 if ( lockf ( d
-> storage_socket
[ 0 ], F_LOCK
, 0 ) < 0 )
380 r
= dynamic_user_pop ( d
, & uid
, & uid_lock_fd
);
388 /* OK, nothing stored yet, let's try to find something useful. While we are working on this release the
389 * lock however, so that nobody else blocks on our NSS lookups. */
390 ( void ) lockf ( d
-> storage_socket
[ 0 ], F_ULOCK
, 0 );
392 /* Let's see if a proper, static user or group by this name exists. Try to take the lock on
393 * /etc/passwd, if that fails with EROFS then /etc is read-only. In that case it's fine if we don't
394 * take the lock, given that users can't be added there anyway in this case. */
395 etc_passwd_lock_fd
= take_etc_passwd_lock ( NULL
);
396 if ( etc_passwd_lock_fd
< 0 && etc_passwd_lock_fd
!= - EROFS
)
397 return etc_passwd_lock_fd
;
399 /* First, let's parse this as numeric UID */
400 r
= parse_uid ( d
-> name
, & uid
);
405 /* OK, this is not a numeric UID. Let's see if there's a user by this name */
406 p
= getpwnam ( d
-> name
);
410 /* Let's see if there's a group by this name */
411 g
= getgrnam ( d
-> name
);
413 /* If the UID/GID of the user/group of the same don't match, refuse operation */
414 if ( uid
!= UID_INVALID
&& uid
!= ( uid_t
) g
-> gr_gid
)
417 uid
= ( uid_t
) g
-> gr_gid
;
421 if ( uid
== UID_INVALID
) {
422 /* No static UID assigned yet, excellent. Let's pick a new dynamic one, and lock it. */
424 uid_lock_fd
= pick_uid ( d
-> name
, & uid
);
429 /* So, we found a working UID/lock combination. Let's see if we actually still need it. */
430 if ( lockf ( d
-> storage_socket
[ 0 ], F_LOCK
, 0 ) < 0 ) {
431 unlink_uid_lock ( uid_lock_fd
, uid
, d
-> name
);
435 r
= dynamic_user_pop ( d
, & new_uid
, & new_uid_lock_fd
);
438 /* OK, something bad happened, let's get rid of the bits we acquired. */
439 unlink_uid_lock ( uid_lock_fd
, uid
, d
-> name
);
443 /* Great! Nothing is stored here, still. Store our newly acquired data. */
445 /* Hmm, so as it appears there's now something stored in the storage socket. Throw away what we
446 * acquired, and use what's stored now. */
448 unlink_uid_lock ( uid_lock_fd
, uid
, d
-> name
);
449 safe_close ( uid_lock_fd
);
452 uid_lock_fd
= new_uid_lock_fd
;
456 /* If the UID/GID was already allocated dynamically, push the data we popped out back in. If it was already
457 * allocated statically, push the UID back too, but do not push the lock fd in. If we allocated the UID
458 * dynamically right here, push that in along with the lock fd for it. */
459 r
= dynamic_user_push ( d
, uid
, uid_lock_fd
);
467 ( void ) lockf ( d
-> storage_socket
[ 0 ], F_ULOCK
, 0 );
471 int dynamic_user_current ( DynamicUser
* d
, uid_t
* ret
) {
472 _cleanup_close_
int lock_fd
= - 1 ;
479 /* 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. */
481 if ( lockf ( d
-> storage_socket
[ 0 ], F_LOCK
, 0 ) < 0 )
484 r
= dynamic_user_pop ( d
, & uid
, & lock_fd
);
488 r
= dynamic_user_push ( d
, uid
, lock_fd
);
496 ( void ) lockf ( d
-> storage_socket
[ 0 ], F_ULOCK
, 0 );
500 DynamicUser
* dynamic_user_ref ( DynamicUser
* d
) {
504 assert ( d
-> n_ref
> 0 );
510 DynamicUser
* dynamic_user_unref ( DynamicUser
* d
) {
514 /* Note that this doesn't actually release any resources itself. If a dynamic user should be fully destroyed
515 * and its UID released, use dynamic_user_destroy() instead. NB: the dynamic user table may contain entries
516 * with no references, which is commonly the case right before a daemon reload. */
518 assert ( d
-> n_ref
> 0 );
524 static int dynamic_user_close ( DynamicUser
* d
) {
525 _cleanup_close_
int lock_fd
= - 1 ;
529 /* Release the user ID, by releasing the lock on it, and emptying the storage socket. After this the user is
530 * unrealized again, much like it was after it the DynamicUser object was first allocated. */
532 if ( lockf ( d
-> storage_socket
[ 0 ], F_LOCK
, 0 ) < 0 )
535 r
= dynamic_user_pop ( d
, & uid
, & lock_fd
);
537 /* User wasn't realized yet, nothing to do. */
544 /* This dynamic user was realized and dynamically allocated. In this case, let's remove the lock file. */
545 unlink_uid_lock ( lock_fd
, uid
, d
-> name
);
549 ( void ) lockf ( d
-> storage_socket
[ 0 ], F_ULOCK
, 0 );
553 DynamicUser
* dynamic_user_destroy ( DynamicUser
* d
) {
557 /* Drop a reference to a DynamicUser object, and destroy the user completely if this was the last
558 * reference. This is called whenever a service is shut down and wants its dynamic UID gone. Note that
559 * dynamic_user_unref() is what is called whenever a service is simply freed, for example during a reload
560 * cycle, where the dynamic users should not be destroyed, but our datastructures should. */
562 dynamic_user_unref ( d
);
567 ( void ) dynamic_user_close ( d
);
568 return dynamic_user_free ( d
);
571 int dynamic_user_serialize ( Manager
* m
, FILE * f
, FDSet
* fds
) {
579 /* Dump the dynamic user database into the manager serialization, to deal with daemon reloads. */
581 HASHMAP_FOREACH ( d
, m
-> dynamic_users
, i
) {
584 copy0
= fdset_put_dup ( fds
, d
-> storage_socket
[ 0 ]);
588 copy1
= fdset_put_dup ( fds
, d
-> storage_socket
[ 1 ]);
592 fprintf ( f
, "dynamic-user=%s %i %i \n " , d
-> name
, copy0
, copy1
);
598 void dynamic_user_deserialize_one ( Manager
* m
, const char * value
, FDSet
* fds
) {
599 _cleanup_free_
char * name
= NULL
, * s0
= NULL
, * s1
= NULL
;
606 /* Parse the serialization again, after a daemon reload */
608 r
= extract_many_words (& value
, NULL
, 0 , & name
, & s0
, & s1
, NULL
);
609 if ( r
!= 3 || ! isempty ( value
)) {
610 log_debug ( "Unable to parse dynamic user line." );
614 if ( safe_atoi ( s0
, & fd0
) < 0 || ! fdset_contains ( fds
, fd0
)) {
615 log_debug ( "Unable to process dynamic user fd specification." );
619 if ( safe_atoi ( s1
, & fd1
) < 0 || ! fdset_contains ( fds
, fd1
)) {
620 log_debug ( "Unable to process dynamic user fd specification." );
624 r
= dynamic_user_add ( m
, name
, ( int []) { fd0
, fd1
}, NULL
);
626 log_debug_errno ( r
, "Failed to add dynamic user: %m" );
630 ( void ) fdset_remove ( fds
, fd0
);
631 ( void ) fdset_remove ( fds
, fd1
);
634 void dynamic_user_vacuum ( Manager
* m
, bool close_user
) {
640 /* Empty the dynamic user database, optionally cleaning up orphaned dynamic users, i.e. destroy and free users
641 * to which no reference exist. This is called after a daemon reload finished, in order to destroy users which
642 * might not be referenced anymore. */
644 HASHMAP_FOREACH ( d
, m
-> dynamic_users
, i
) {
649 log_debug ( "Removing orphaned dynamic user %s" , d
-> name
);
650 ( void ) dynamic_user_close ( d
);
653 dynamic_user_free ( d
);
657 int dynamic_user_lookup_uid ( Manager
* m
, uid_t uid
, char ** ret
) {
658 char lock_path
[ strlen ( "/run/systemd/dynamic-uid/" ) + DECIMAL_STR_MAX ( uid_t
) + 1 ];
659 _cleanup_free_
char * user
= NULL
;
666 /* A friendly way to translate a dynamic user's UID into a name. */
667 if (! uid_is_dynamic ( uid
))
670 xsprintf ( lock_path
, "/run/systemd/dynamic-uid/" UID_FMT
, uid
);
671 r
= read_one_line_file ( lock_path
, & user
);
677 /* The lock file might be stale, hence let's verify the data before we return it */
678 r
= dynamic_user_lookup_name ( m
, user
, & check_uid
);
681 if ( check_uid
!= uid
) /* lock file doesn't match our own idea */
690 int dynamic_user_lookup_name ( Manager
* m
, const char * name
, uid_t
* ret
) {
698 /* A friendly call for translating a dynamic user's name into its UID */
700 d
= hashmap_get ( m
-> dynamic_users
, name
);
704 r
= dynamic_user_current ( d
, ret
);
705 if ( r
== - EAGAIN
) /* not realized yet? */
711 int dynamic_creds_acquire ( DynamicCreds
* creds
, Manager
* m
, const char * user
, const char * group
) {
712 bool acquired
= false ;
718 /* A DynamicUser object encapsulates an allocation of both a UID and a GID for a specific name. However, some
719 * services use different user and groups. For cases like that there's DynamicCreds containing a pair of user
720 * and group. This call allocates a pair. */
722 if (! creds
-> user
&& user
) {
723 r
= dynamic_user_acquire ( m
, user
, & creds
-> user
);
732 if ( creds
-> user
&& (! group
|| streq_ptr ( user
, group
)))
733 creds
-> group
= dynamic_user_ref ( creds
-> user
);
735 r
= dynamic_user_acquire ( m
, group
, & creds
-> group
);
738 creds
-> user
= dynamic_user_unref ( creds
-> user
);
747 int dynamic_creds_realize ( DynamicCreds
* creds
, uid_t
* uid
, gid_t
* gid
) {
748 uid_t u
= UID_INVALID
;
749 gid_t g
= GID_INVALID
;
756 /* Realize both the referenced user and group */
759 r
= dynamic_user_realize ( creds
-> user
, & u
);
764 if ( creds
-> group
&& creds
-> group
!= creds
-> user
) {
765 r
= dynamic_user_realize ( creds
-> group
, & g
);
777 void dynamic_creds_unref ( DynamicCreds
* creds
) {
780 creds
-> user
= dynamic_user_unref ( creds
-> user
);
781 creds
-> group
= dynamic_user_unref ( creds
-> group
);
784 void dynamic_creds_destroy ( DynamicCreds
* creds
) {
787 creds
-> user
= dynamic_user_destroy ( creds
-> user
);
788 creds
-> group
= dynamic_user_destroy ( creds
-> group
);