]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/chase-symlinks.c
path-util: Add path_make_relative_cwd()
[thirdparty/systemd.git] / src / basic / chase-symlinks.c
CommitLineData
f4351959
LP
1/* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3#include <linux/magic.h>
4
5#include "alloc-util.h"
6#include "chase-symlinks.h"
7#include "fd-util.h"
01bebba3 8#include "fileio.h"
f4351959
LP
9#include "fs-util.h"
10#include "glyph-util.h"
11#include "log.h"
12#include "path-util.h"
13#include "string-util.h"
14#include "user-util.h"
15
16bool unsafe_transition(const struct stat *a, const struct stat *b) {
17 /* Returns true if the transition from a to b is safe, i.e. that we never transition from unprivileged to
18 * privileged files or directories. Why bother? So that unprivileged code can't symlink to privileged files
19 * making us believe we read something safe even though it isn't safe in the specific context we open it in. */
20
21 if (a->st_uid == 0) /* Transitioning from privileged to unprivileged is always fine */
22 return false;
23
24 return a->st_uid != b->st_uid; /* Otherwise we need to stay within the same UID */
25}
26
8f47f880 27static int log_unsafe_transition(int a, int b, const char *path, ChaseSymlinksFlags flags) {
f4351959
LP
28 _cleanup_free_ char *n1 = NULL, *n2 = NULL, *user_a = NULL, *user_b = NULL;
29 struct stat st;
30
31 if (!FLAGS_SET(flags, CHASE_WARN))
32 return -ENOLINK;
33
34 (void) fd_get_path(a, &n1);
35 (void) fd_get_path(b, &n2);
36
37 if (fstat(a, &st) == 0)
38 user_a = uid_to_name(st.st_uid);
39 if (fstat(b, &st) == 0)
40 user_b = uid_to_name(st.st_uid);
41
42 return log_warning_errno(SYNTHETIC_ERRNO(ENOLINK),
43 "Detected unsafe path transition %s (owned by %s) %s %s (owned by %s) during canonicalization of %s.",
fc03e80c 44 strna(n1), strna(user_a), special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), strna(n2), strna(user_b), path);
f4351959
LP
45}
46
8f47f880 47static int log_autofs_mount_point(int fd, const char *path, ChaseSymlinksFlags flags) {
f4351959
LP
48 _cleanup_free_ char *n1 = NULL;
49
50 if (!FLAGS_SET(flags, CHASE_WARN))
51 return -EREMOTE;
52
53 (void) fd_get_path(fd, &n1);
54
55 return log_warning_errno(SYNTHETIC_ERRNO(EREMOTE),
56 "Detected autofs mount point %s during canonicalization of %s.",
57 strna(n1), path);
58}
59
8f47f880
LP
60int chase_symlinks(
61 const char *path,
62 const char *original_root,
63 ChaseSymlinksFlags flags,
64 char **ret_path,
65 int *ret_fd) {
66
f4351959
LP
67 _cleanup_free_ char *buffer = NULL, *done = NULL, *root = NULL;
68 _cleanup_close_ int fd = -1;
69 unsigned max_follow = CHASE_SYMLINKS_MAX; /* how many symlinks to follow before giving up and returning ELOOP */
70 bool exists = true, append_trail_slash = false;
71 struct stat previous_stat;
72 const char *todo;
73 int r;
74
75 assert(path);
76
77 /* Either the file may be missing, or we return an fd to the final object, but both make no sense */
78 if ((flags & CHASE_NONEXISTENT) && ret_fd)
79 return -EINVAL;
80
81 if ((flags & CHASE_STEP) && ret_fd)
82 return -EINVAL;
83
84 if (isempty(path))
85 return -EINVAL;
86
87 /* This is a lot like canonicalize_file_name(), but takes an additional "root" parameter, that allows following
88 * symlinks relative to a root directory, instead of the root of the host.
89 *
90 * Note that "root" primarily matters if we encounter an absolute symlink. It is also used when following
91 * relative symlinks to ensure they cannot be used to "escape" the root directory. The path parameter passed is
92 * assumed to be already prefixed by it, except if the CHASE_PREFIX_ROOT flag is set, in which case it is first
93 * prefixed accordingly.
94 *
95 * Algorithmically this operates on two path buffers: "done" are the components of the path we already
96 * processed and resolved symlinks, "." and ".." of. "todo" are the components of the path we still need to
97 * process. On each iteration, we move one component from "todo" to "done", processing it's special meaning
98 * each time. The "todo" path always starts with at least one slash, the "done" path always ends in no
99 * slash. We always keep an O_PATH fd to the component we are currently processing, thus keeping lookup races
100 * to a minimum.
101 *
102 * Suggested usage: whenever you want to canonicalize a path, use this function. Pass the absolute path you got
103 * as-is: fully qualified and relative to your host's root. Optionally, specify the root parameter to tell this
104 * function what to do when encountering a symlink with an absolute path as directory: prefix it by the
105 * specified path.
106 *
107 * There are five ways to invoke this function:
108 *
109 * 1. Without CHASE_STEP or ret_fd: in this case the path is resolved and the normalized path is
110 * returned in `ret_path`. The return value is < 0 on error. If CHASE_NONEXISTENT is also set, 0
111 * is returned if the file doesn't exist, > 0 otherwise. If CHASE_NONEXISTENT is not set, >= 0 is
112 * returned if the destination was found, -ENOENT if it wasn't.
113 *
114 * 2. With ret_fd: in this case the destination is opened after chasing it as O_PATH and this file
115 * descriptor is returned as return value. This is useful to open files relative to some root
116 * directory. Note that the returned O_PATH file descriptors must be converted into a regular one (using
117 * fd_reopen() or such) before it can be used for reading/writing. ret_fd may not be combined with
118 * CHASE_NONEXISTENT.
119 *
120 * 3. With CHASE_STEP: in this case only a single step of the normalization is executed, i.e. only the first
121 * symlink or ".." component of the path is resolved, and the resulting path is returned. This is useful if
122 * a caller wants to trace the path through the file system verbosely. Returns < 0 on error, > 0 if the
123 * path is fully normalized, and == 0 for each normalization step. This may be combined with
124 * CHASE_NONEXISTENT, in which case 1 is returned when a component is not found.
125 *
126 * 4. With CHASE_SAFE: in this case the path must not contain unsafe transitions, i.e. transitions from
127 * unprivileged to privileged files or directories. In such cases the return value is -ENOLINK. If
9154bd57
ZJS
128 * CHASE_WARN is also set, a warning describing the unsafe transition is emitted. CHASE_WARN cannot
129 * be used in PID 1.
f4351959
LP
130 *
131 * 5. With CHASE_NO_AUTOFS: in this case if an autofs mount point is encountered, path normalization
132 * is aborted and -EREMOTE is returned. If CHASE_WARN is also set, a warning showing the path of
9154bd57 133 * the mount point is emitted. CHASE_WARN cannot be used in PID 1.
f4351959
LP
134 */
135
136 /* A root directory of "/" or "" is identical to none */
137 if (empty_or_root(original_root))
138 original_root = NULL;
139
140 if (!original_root && !ret_path && !(flags & (CHASE_NONEXISTENT|CHASE_NO_AUTOFS|CHASE_SAFE|CHASE_STEP)) && ret_fd) {
141 /* Shortcut the ret_fd case if the caller isn't interested in the actual path and has no root set
142 * and doesn't care about any of the other special features we provide either. */
143 r = open(path, O_PATH|O_CLOEXEC|((flags & CHASE_NOFOLLOW) ? O_NOFOLLOW : 0));
144 if (r < 0)
145 return -errno;
146
147 *ret_fd = r;
148 return 0;
149 }
150
151 if (original_root) {
152 r = path_make_absolute_cwd(original_root, &root);
153 if (r < 0)
154 return r;
155
156 /* Simplify the root directory, so that it has no duplicate slashes and nothing at the
157 * end. While we won't resolve the root path we still simplify it. Note that dropping the
158 * trailing slash should not change behaviour, since when opening it we specify O_DIRECTORY
159 * anyway. Moreover at the end of this function after processing everything we'll always turn
160 * the empty string back to "/". */
161 delete_trailing_chars(root, "/");
162 path_simplify(root);
163
164 if (flags & CHASE_PREFIX_ROOT) {
7b9be862
LP
165 buffer = path_join(root, path);
166 if (!buffer)
167 return -ENOMEM;
f4351959
LP
168 }
169 }
170
7b9be862
LP
171 if (!buffer) {
172 r = path_make_absolute_cwd(path, &buffer);
173 if (r < 0)
174 return r;
175 }
f4351959 176
69cf392f 177 fd = open(empty_to_root(root), O_CLOEXEC|O_DIRECTORY|O_PATH);
f4351959
LP
178 if (fd < 0)
179 return -errno;
180
181 if (flags & CHASE_SAFE)
182 if (fstat(fd, &previous_stat) < 0)
183 return -errno;
184
185 if (flags & CHASE_TRAIL_SLASH)
186 append_trail_slash = endswith(buffer, "/") || endswith(buffer, "/.");
187
188 if (root) {
189 /* If we are operating on a root directory, let's take the root directory as it is. */
190
191 todo = path_startswith(buffer, root);
192 if (!todo)
193 return log_full_errno(flags & CHASE_WARN ? LOG_WARNING : LOG_DEBUG,
194 SYNTHETIC_ERRNO(ECHRNG),
195 "Specified path '%s' is outside of specified root directory '%s', refusing to resolve.",
196 path, root);
197
198 done = strdup(root);
199 } else {
200 todo = buffer;
201 done = strdup("/");
202 }
0ac6cdd6
LP
203 if (!done)
204 return -ENOMEM;
f4351959
LP
205
206 for (;;) {
207 _cleanup_free_ char *first = NULL;
208 _cleanup_close_ int child = -1;
209 struct stat st;
210 const char *e;
211
860f4c6a 212 r = path_find_first_component(&todo, /* accept_dot_dot= */ true, &e);
f4351959
LP
213 if (r < 0)
214 return r;
215 if (r == 0) { /* We reached the end. */
216 if (append_trail_slash)
217 if (!strextend(&done, "/"))
218 return -ENOMEM;
219 break;
220 }
221
222 first = strndup(e, r);
223 if (!first)
224 return -ENOMEM;
225
226 /* Two dots? Then chop off the last bit of what we already found out. */
227 if (path_equal(first, "..")) {
228 _cleanup_free_ char *parent = NULL;
229 _cleanup_close_ int fd_parent = -1;
230
231 /* If we already are at the top, then going up will not change anything. This is in-line with
232 * how the kernel handles this. */
233 if (empty_or_root(done))
234 continue;
235
57f9ca3a
LP
236 r = path_extract_directory(done, &parent);
237 if (r < 0)
238 return r;
f4351959
LP
239
240 /* Don't allow this to leave the root dir. */
241 if (root &&
242 path_startswith(done, root) &&
243 !path_startswith(parent, root))
244 continue;
245
246 free_and_replace(done, parent);
247
248 if (flags & CHASE_STEP)
249 goto chased_one;
250
251 fd_parent = openat(fd, "..", O_CLOEXEC|O_NOFOLLOW|O_PATH);
252 if (fd_parent < 0)
253 return -errno;
254
255 if (flags & CHASE_SAFE) {
256 if (fstat(fd_parent, &st) < 0)
257 return -errno;
258
259 if (unsafe_transition(&previous_stat, &st))
260 return log_unsafe_transition(fd, fd_parent, path, flags);
261
262 previous_stat = st;
263 }
264
ee3455cf 265 close_and_replace(fd, fd_parent);
f4351959
LP
266
267 continue;
268 }
269
270 /* Otherwise let's see what this is. */
271 child = openat(fd, first, O_CLOEXEC|O_NOFOLLOW|O_PATH);
272 if (child < 0) {
273 if (errno == ENOENT &&
274 (flags & CHASE_NONEXISTENT) &&
275 (isempty(todo) || path_is_safe(todo))) {
276 /* If CHASE_NONEXISTENT is set, and the path does not exist, then
277 * that's OK, return what we got so far. But don't allow this if the
278 * remaining path contains "../" or something else weird. */
279
280 if (!path_extend(&done, first, todo))
281 return -ENOMEM;
282
283 exists = false;
284 break;
285 }
286
287 return -errno;
288 }
289
290 if (fstat(child, &st) < 0)
291 return -errno;
292 if ((flags & CHASE_SAFE) &&
293 unsafe_transition(&previous_stat, &st))
294 return log_unsafe_transition(fd, child, path, flags);
295
296 previous_stat = st;
297
298 if ((flags & CHASE_NO_AUTOFS) &&
299 fd_is_fs_type(child, AUTOFS_SUPER_MAGIC) > 0)
300 return log_autofs_mount_point(child, path, flags);
301
302 if (S_ISLNK(st.st_mode) && !((flags & CHASE_NOFOLLOW) && isempty(todo))) {
303 _cleanup_free_ char *destination = NULL;
304
305 /* This is a symlink, in this case read the destination. But let's make sure we
306 * don't follow symlinks without bounds. */
307 if (--max_follow <= 0)
308 return -ELOOP;
309
310 r = readlinkat_malloc(fd, first, &destination);
311 if (r < 0)
312 return r;
313 if (isempty(destination))
314 return -EINVAL;
315
316 if (path_is_absolute(destination)) {
317
318 /* An absolute destination. Start the loop from the beginning, but use the root
319 * directory as base. */
320
321 safe_close(fd);
69cf392f 322 fd = open(empty_to_root(root), O_CLOEXEC|O_DIRECTORY|O_PATH);
f4351959
LP
323 if (fd < 0)
324 return -errno;
325
326 if (flags & CHASE_SAFE) {
327 if (fstat(fd, &st) < 0)
328 return -errno;
329
330 if (unsafe_transition(&previous_stat, &st))
331 return log_unsafe_transition(child, fd, path, flags);
332
333 previous_stat = st;
334 }
335
336 /* Note that we do not revalidate the root, we take it as is. */
337 r = free_and_strdup(&done, empty_to_root(root));
338 if (r < 0)
339 return r;
340 }
341
342 /* Prefix what's left to do with what we just read, and start the loop again, but
343 * remain in the current directory. */
344 if (!path_extend(&destination, todo))
345 return -ENOMEM;
346
347 free_and_replace(buffer, destination);
348 todo = buffer;
349
350 if (flags & CHASE_STEP)
351 goto chased_one;
352
353 continue;
354 }
355
356 /* If this is not a symlink, then let's just add the name we read to what we already verified. */
357 if (!path_extend(&done, first))
358 return -ENOMEM;
359
360 /* And iterate again, but go one directory further down. */
ee3455cf 361 close_and_replace(fd, child);
f4351959
LP
362 }
363
364 if (ret_path)
365 *ret_path = TAKE_PTR(done);
366
367 if (ret_fd) {
368 /* Return the O_PATH fd we currently are looking to the caller. It can translate it to a
369 * proper fd by opening /proc/self/fd/xyz. */
370
371 assert(fd >= 0);
372 *ret_fd = TAKE_FD(fd);
373 }
374
375 if (flags & CHASE_STEP)
376 return 1;
377
378 return exists;
379
380chased_one:
381 if (ret_path) {
382 const char *e;
383
384 /* todo may contain slashes at the beginning. */
860f4c6a 385 r = path_find_first_component(&todo, /* accept_dot_dot= */ true, &e);
f4351959
LP
386 if (r < 0)
387 return r;
388 if (r == 0)
389 *ret_path = TAKE_PTR(done);
390 else {
391 char *c;
392
393 c = path_join(done, e);
394 if (!c)
395 return -ENOMEM;
396
397 *ret_path = c;
398 }
399 }
400
401 return 0;
402}
403
404int chase_symlinks_and_open(
405 const char *path,
406 const char *root,
8f47f880 407 ChaseSymlinksFlags chase_flags,
f4351959
LP
408 int open_flags,
409 char **ret_path) {
410
411 _cleanup_close_ int path_fd = -1;
412 _cleanup_free_ char *p = NULL;
413 int r;
414
81a7eac1 415 if (chase_flags & (CHASE_NONEXISTENT|CHASE_STEP))
f4351959
LP
416 return -EINVAL;
417
418 if (empty_or_root(root) && !ret_path && (chase_flags & (CHASE_NO_AUTOFS|CHASE_SAFE)) == 0) {
419 /* Shortcut this call if none of the special features of this call are requested */
69570232 420 r = open(path, open_flags | (FLAGS_SET(chase_flags, CHASE_NOFOLLOW) ? O_NOFOLLOW : 0));
f4351959
LP
421 if (r < 0)
422 return -errno;
423
424 return r;
425 }
426
427 r = chase_symlinks(path, root, chase_flags, ret_path ? &p : NULL, &path_fd);
428 if (r < 0)
429 return r;
430 assert(path_fd >= 0);
431
432 r = fd_reopen(path_fd, open_flags);
433 if (r < 0)
434 return r;
435
436 if (ret_path)
437 *ret_path = TAKE_PTR(p);
438
439 return r;
440}
441
442int chase_symlinks_and_opendir(
443 const char *path,
444 const char *root,
8f47f880 445 ChaseSymlinksFlags chase_flags,
f4351959
LP
446 char **ret_path,
447 DIR **ret_dir) {
448
449 _cleanup_close_ int path_fd = -1;
450 _cleanup_free_ char *p = NULL;
451 DIR *d;
452 int r;
453
454 if (!ret_dir)
455 return -EINVAL;
81a7eac1 456 if (chase_flags & (CHASE_NONEXISTENT|CHASE_STEP))
f4351959
LP
457 return -EINVAL;
458
459 if (empty_or_root(root) && !ret_path && (chase_flags & (CHASE_NO_AUTOFS|CHASE_SAFE)) == 0) {
460 /* Shortcut this call if none of the special features of this call are requested */
461 d = opendir(path);
462 if (!d)
463 return -errno;
464
465 *ret_dir = d;
466 return 0;
467 }
468
469 r = chase_symlinks(path, root, chase_flags, ret_path ? &p : NULL, &path_fd);
470 if (r < 0)
471 return r;
472 assert(path_fd >= 0);
473
474 d = opendir(FORMAT_PROC_FD_PATH(path_fd));
475 if (!d)
476 return -errno;
477
478 if (ret_path)
479 *ret_path = TAKE_PTR(p);
480
481 *ret_dir = d;
482 return 0;
483}
484
485int chase_symlinks_and_stat(
486 const char *path,
487 const char *root,
8f47f880 488 ChaseSymlinksFlags chase_flags,
f4351959
LP
489 char **ret_path,
490 struct stat *ret_stat,
491 int *ret_fd) {
492
493 _cleanup_close_ int path_fd = -1;
494 _cleanup_free_ char *p = NULL;
495 int r;
496
497 assert(path);
498 assert(ret_stat);
499
81a7eac1 500 if (chase_flags & (CHASE_NONEXISTENT|CHASE_STEP))
f4351959
LP
501 return -EINVAL;
502
37b9bc56 503 if (empty_or_root(root) && !ret_path && (chase_flags & (CHASE_NO_AUTOFS|CHASE_SAFE)) == 0 && !ret_fd) {
f4351959 504 /* Shortcut this call if none of the special features of this call are requested */
69570232
LP
505
506 if (fstatat(AT_FDCWD, path, ret_stat, FLAGS_SET(chase_flags, CHASE_NOFOLLOW) ? AT_SYMLINK_NOFOLLOW : 0) < 0)
f4351959
LP
507 return -errno;
508
509 return 1;
510 }
511
512 r = chase_symlinks(path, root, chase_flags, ret_path ? &p : NULL, &path_fd);
513 if (r < 0)
514 return r;
515 assert(path_fd >= 0);
516
517 if (fstat(path_fd, ret_stat) < 0)
518 return -errno;
519
520 if (ret_path)
521 *ret_path = TAKE_PTR(p);
2b2caea2
LP
522 if (ret_fd)
523 *ret_fd = TAKE_FD(path_fd);
524
525 return 1;
526}
527
528int chase_symlinks_and_access(
529 const char *path,
530 const char *root,
531 ChaseSymlinksFlags chase_flags,
532 int access_mode,
533 char **ret_path,
534 int *ret_fd) {
535
536 _cleanup_close_ int path_fd = -1;
537 _cleanup_free_ char *p = NULL;
538 int r;
539
540 assert(path);
541
542 if (chase_flags & (CHASE_NONEXISTENT|CHASE_STEP))
543 return -EINVAL;
544
545 if (empty_or_root(root) && !ret_path && (chase_flags & (CHASE_NO_AUTOFS|CHASE_SAFE)) == 0 && !ret_fd) {
546 /* Shortcut this call if none of the special features of this call are requested */
547
548 if (faccessat(AT_FDCWD, path, access_mode, FLAGS_SET(chase_flags, CHASE_NOFOLLOW) ? AT_SYMLINK_NOFOLLOW : 0) < 0)
549 return -errno;
550
551 return 1;
552 }
553
554 r = chase_symlinks(path, root, chase_flags, ret_path ? &p : NULL, &path_fd);
555 if (r < 0)
556 return r;
557 assert(path_fd >= 0);
558
559 r = access_fd(path_fd, access_mode);
560 if (r < 0)
561 return r;
562
563 if (ret_path)
564 *ret_path = TAKE_PTR(p);
f4351959
LP
565 if (ret_fd)
566 *ret_fd = TAKE_FD(path_fd);
567
568 return 1;
569}
01bebba3
LP
570
571int chase_symlinks_and_fopen_unlocked(
572 const char *path,
573 const char *root,
8f47f880 574 ChaseSymlinksFlags chase_flags,
01bebba3
LP
575 const char *open_flags,
576 char **ret_path,
577 FILE **ret_file) {
578
579 _cleanup_free_ char *final_path = NULL;
580 _cleanup_close_ int fd = -1;
581 int mode_flags, r;
582
583 assert(path);
584 assert(open_flags);
585 assert(ret_file);
586
587 mode_flags = fopen_mode_to_flags(open_flags);
588 if (mode_flags < 0)
589 return mode_flags;
590
591 fd = chase_symlinks_and_open(path, root, chase_flags, mode_flags, ret_path ? &final_path : NULL);
592 if (fd < 0)
593 return fd;
594
595 r = take_fdopen_unlocked(&fd, open_flags, ret_file);
596 if (r < 0)
597 return r;
598
599 if (ret_path)
600 *ret_path = TAKE_PTR(final_path);
601
602 return 0;
603}