]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/chase-symlinks.c
network: fix use-after-free
[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
128 * CHASE_WARN is also set, a warning describing the unsafe transition is emitted.
129 *
130 * 5. With CHASE_NO_AUTOFS: in this case if an autofs mount point is encountered, path normalization
131 * is aborted and -EREMOTE is returned. If CHASE_WARN is also set, a warning showing the path of
132 * the mount point is emitted.
133 */
134
135 /* A root directory of "/" or "" is identical to none */
136 if (empty_or_root(original_root))
137 original_root = NULL;
138
139 if (!original_root && !ret_path && !(flags & (CHASE_NONEXISTENT|CHASE_NO_AUTOFS|CHASE_SAFE|CHASE_STEP)) && ret_fd) {
140 /* Shortcut the ret_fd case if the caller isn't interested in the actual path and has no root set
141 * and doesn't care about any of the other special features we provide either. */
142 r = open(path, O_PATH|O_CLOEXEC|((flags & CHASE_NOFOLLOW) ? O_NOFOLLOW : 0));
143 if (r < 0)
144 return -errno;
145
146 *ret_fd = r;
147 return 0;
148 }
149
150 if (original_root) {
151 r = path_make_absolute_cwd(original_root, &root);
152 if (r < 0)
153 return r;
154
155 /* Simplify the root directory, so that it has no duplicate slashes and nothing at the
156 * end. While we won't resolve the root path we still simplify it. Note that dropping the
157 * trailing slash should not change behaviour, since when opening it we specify O_DIRECTORY
158 * anyway. Moreover at the end of this function after processing everything we'll always turn
159 * the empty string back to "/". */
160 delete_trailing_chars(root, "/");
161 path_simplify(root);
162
163 if (flags & CHASE_PREFIX_ROOT) {
7b9be862
LP
164 buffer = path_join(root, path);
165 if (!buffer)
166 return -ENOMEM;
f4351959
LP
167 }
168 }
169
7b9be862
LP
170 if (!buffer) {
171 r = path_make_absolute_cwd(path, &buffer);
172 if (r < 0)
173 return r;
174 }
f4351959 175
69cf392f 176 fd = open(empty_to_root(root), O_CLOEXEC|O_DIRECTORY|O_PATH);
f4351959
LP
177 if (fd < 0)
178 return -errno;
179
180 if (flags & CHASE_SAFE)
181 if (fstat(fd, &previous_stat) < 0)
182 return -errno;
183
184 if (flags & CHASE_TRAIL_SLASH)
185 append_trail_slash = endswith(buffer, "/") || endswith(buffer, "/.");
186
187 if (root) {
188 /* If we are operating on a root directory, let's take the root directory as it is. */
189
190 todo = path_startswith(buffer, root);
191 if (!todo)
192 return log_full_errno(flags & CHASE_WARN ? LOG_WARNING : LOG_DEBUG,
193 SYNTHETIC_ERRNO(ECHRNG),
194 "Specified path '%s' is outside of specified root directory '%s', refusing to resolve.",
195 path, root);
196
197 done = strdup(root);
198 } else {
199 todo = buffer;
200 done = strdup("/");
201 }
0ac6cdd6
LP
202 if (!done)
203 return -ENOMEM;
f4351959
LP
204
205 for (;;) {
206 _cleanup_free_ char *first = NULL;
207 _cleanup_close_ int child = -1;
208 struct stat st;
209 const char *e;
210
860f4c6a 211 r = path_find_first_component(&todo, /* accept_dot_dot= */ true, &e);
f4351959
LP
212 if (r < 0)
213 return r;
214 if (r == 0) { /* We reached the end. */
215 if (append_trail_slash)
216 if (!strextend(&done, "/"))
217 return -ENOMEM;
218 break;
219 }
220
221 first = strndup(e, r);
222 if (!first)
223 return -ENOMEM;
224
225 /* Two dots? Then chop off the last bit of what we already found out. */
226 if (path_equal(first, "..")) {
227 _cleanup_free_ char *parent = NULL;
228 _cleanup_close_ int fd_parent = -1;
229
230 /* If we already are at the top, then going up will not change anything. This is in-line with
231 * how the kernel handles this. */
232 if (empty_or_root(done))
233 continue;
234
57f9ca3a
LP
235 r = path_extract_directory(done, &parent);
236 if (r < 0)
237 return r;
f4351959
LP
238
239 /* Don't allow this to leave the root dir. */
240 if (root &&
241 path_startswith(done, root) &&
242 !path_startswith(parent, root))
243 continue;
244
245 free_and_replace(done, parent);
246
247 if (flags & CHASE_STEP)
248 goto chased_one;
249
250 fd_parent = openat(fd, "..", O_CLOEXEC|O_NOFOLLOW|O_PATH);
251 if (fd_parent < 0)
252 return -errno;
253
254 if (flags & CHASE_SAFE) {
255 if (fstat(fd_parent, &st) < 0)
256 return -errno;
257
258 if (unsafe_transition(&previous_stat, &st))
259 return log_unsafe_transition(fd, fd_parent, path, flags);
260
261 previous_stat = st;
262 }
263
ee3455cf 264 close_and_replace(fd, fd_parent);
f4351959
LP
265
266 continue;
267 }
268
269 /* Otherwise let's see what this is. */
270 child = openat(fd, first, O_CLOEXEC|O_NOFOLLOW|O_PATH);
271 if (child < 0) {
272 if (errno == ENOENT &&
273 (flags & CHASE_NONEXISTENT) &&
274 (isempty(todo) || path_is_safe(todo))) {
275 /* If CHASE_NONEXISTENT is set, and the path does not exist, then
276 * that's OK, return what we got so far. But don't allow this if the
277 * remaining path contains "../" or something else weird. */
278
279 if (!path_extend(&done, first, todo))
280 return -ENOMEM;
281
282 exists = false;
283 break;
284 }
285
286 return -errno;
287 }
288
289 if (fstat(child, &st) < 0)
290 return -errno;
291 if ((flags & CHASE_SAFE) &&
292 unsafe_transition(&previous_stat, &st))
293 return log_unsafe_transition(fd, child, path, flags);
294
295 previous_stat = st;
296
297 if ((flags & CHASE_NO_AUTOFS) &&
298 fd_is_fs_type(child, AUTOFS_SUPER_MAGIC) > 0)
299 return log_autofs_mount_point(child, path, flags);
300
301 if (S_ISLNK(st.st_mode) && !((flags & CHASE_NOFOLLOW) && isempty(todo))) {
302 _cleanup_free_ char *destination = NULL;
303
304 /* This is a symlink, in this case read the destination. But let's make sure we
305 * don't follow symlinks without bounds. */
306 if (--max_follow <= 0)
307 return -ELOOP;
308
309 r = readlinkat_malloc(fd, first, &destination);
310 if (r < 0)
311 return r;
312 if (isempty(destination))
313 return -EINVAL;
314
315 if (path_is_absolute(destination)) {
316
317 /* An absolute destination. Start the loop from the beginning, but use the root
318 * directory as base. */
319
320 safe_close(fd);
69cf392f 321 fd = open(empty_to_root(root), O_CLOEXEC|O_DIRECTORY|O_PATH);
f4351959
LP
322 if (fd < 0)
323 return -errno;
324
325 if (flags & CHASE_SAFE) {
326 if (fstat(fd, &st) < 0)
327 return -errno;
328
329 if (unsafe_transition(&previous_stat, &st))
330 return log_unsafe_transition(child, fd, path, flags);
331
332 previous_stat = st;
333 }
334
335 /* Note that we do not revalidate the root, we take it as is. */
336 r = free_and_strdup(&done, empty_to_root(root));
337 if (r < 0)
338 return r;
339 }
340
341 /* Prefix what's left to do with what we just read, and start the loop again, but
342 * remain in the current directory. */
343 if (!path_extend(&destination, todo))
344 return -ENOMEM;
345
346 free_and_replace(buffer, destination);
347 todo = buffer;
348
349 if (flags & CHASE_STEP)
350 goto chased_one;
351
352 continue;
353 }
354
355 /* If this is not a symlink, then let's just add the name we read to what we already verified. */
356 if (!path_extend(&done, first))
357 return -ENOMEM;
358
359 /* And iterate again, but go one directory further down. */
ee3455cf 360 close_and_replace(fd, child);
f4351959
LP
361 }
362
363 if (ret_path)
364 *ret_path = TAKE_PTR(done);
365
366 if (ret_fd) {
367 /* Return the O_PATH fd we currently are looking to the caller. It can translate it to a
368 * proper fd by opening /proc/self/fd/xyz. */
369
370 assert(fd >= 0);
371 *ret_fd = TAKE_FD(fd);
372 }
373
374 if (flags & CHASE_STEP)
375 return 1;
376
377 return exists;
378
379chased_one:
380 if (ret_path) {
381 const char *e;
382
383 /* todo may contain slashes at the beginning. */
860f4c6a 384 r = path_find_first_component(&todo, /* accept_dot_dot= */ true, &e);
f4351959
LP
385 if (r < 0)
386 return r;
387 if (r == 0)
388 *ret_path = TAKE_PTR(done);
389 else {
390 char *c;
391
392 c = path_join(done, e);
393 if (!c)
394 return -ENOMEM;
395
396 *ret_path = c;
397 }
398 }
399
400 return 0;
401}
402
403int chase_symlinks_and_open(
404 const char *path,
405 const char *root,
8f47f880 406 ChaseSymlinksFlags chase_flags,
f4351959
LP
407 int open_flags,
408 char **ret_path) {
409
410 _cleanup_close_ int path_fd = -1;
411 _cleanup_free_ char *p = NULL;
412 int r;
413
81a7eac1 414 if (chase_flags & (CHASE_NONEXISTENT|CHASE_STEP))
f4351959
LP
415 return -EINVAL;
416
417 if (empty_or_root(root) && !ret_path && (chase_flags & (CHASE_NO_AUTOFS|CHASE_SAFE)) == 0) {
418 /* Shortcut this call if none of the special features of this call are requested */
69570232 419 r = open(path, open_flags | (FLAGS_SET(chase_flags, CHASE_NOFOLLOW) ? O_NOFOLLOW : 0));
f4351959
LP
420 if (r < 0)
421 return -errno;
422
423 return r;
424 }
425
426 r = chase_symlinks(path, root, chase_flags, ret_path ? &p : NULL, &path_fd);
427 if (r < 0)
428 return r;
429 assert(path_fd >= 0);
430
431 r = fd_reopen(path_fd, open_flags);
432 if (r < 0)
433 return r;
434
435 if (ret_path)
436 *ret_path = TAKE_PTR(p);
437
438 return r;
439}
440
441int chase_symlinks_and_opendir(
442 const char *path,
443 const char *root,
8f47f880 444 ChaseSymlinksFlags chase_flags,
f4351959
LP
445 char **ret_path,
446 DIR **ret_dir) {
447
448 _cleanup_close_ int path_fd = -1;
449 _cleanup_free_ char *p = NULL;
450 DIR *d;
451 int r;
452
453 if (!ret_dir)
454 return -EINVAL;
81a7eac1 455 if (chase_flags & (CHASE_NONEXISTENT|CHASE_STEP))
f4351959
LP
456 return -EINVAL;
457
458 if (empty_or_root(root) && !ret_path && (chase_flags & (CHASE_NO_AUTOFS|CHASE_SAFE)) == 0) {
459 /* Shortcut this call if none of the special features of this call are requested */
460 d = opendir(path);
461 if (!d)
462 return -errno;
463
464 *ret_dir = d;
465 return 0;
466 }
467
468 r = chase_symlinks(path, root, chase_flags, ret_path ? &p : NULL, &path_fd);
469 if (r < 0)
470 return r;
471 assert(path_fd >= 0);
472
473 d = opendir(FORMAT_PROC_FD_PATH(path_fd));
474 if (!d)
475 return -errno;
476
477 if (ret_path)
478 *ret_path = TAKE_PTR(p);
479
480 *ret_dir = d;
481 return 0;
482}
483
484int chase_symlinks_and_stat(
485 const char *path,
486 const char *root,
8f47f880 487 ChaseSymlinksFlags chase_flags,
f4351959
LP
488 char **ret_path,
489 struct stat *ret_stat,
490 int *ret_fd) {
491
492 _cleanup_close_ int path_fd = -1;
493 _cleanup_free_ char *p = NULL;
494 int r;
495
496 assert(path);
497 assert(ret_stat);
498
81a7eac1 499 if (chase_flags & (CHASE_NONEXISTENT|CHASE_STEP))
f4351959
LP
500 return -EINVAL;
501
37b9bc56 502 if (empty_or_root(root) && !ret_path && (chase_flags & (CHASE_NO_AUTOFS|CHASE_SAFE)) == 0 && !ret_fd) {
f4351959 503 /* Shortcut this call if none of the special features of this call are requested */
69570232
LP
504
505 if (fstatat(AT_FDCWD, path, ret_stat, FLAGS_SET(chase_flags, CHASE_NOFOLLOW) ? AT_SYMLINK_NOFOLLOW : 0) < 0)
f4351959
LP
506 return -errno;
507
508 return 1;
509 }
510
511 r = chase_symlinks(path, root, chase_flags, ret_path ? &p : NULL, &path_fd);
512 if (r < 0)
513 return r;
514 assert(path_fd >= 0);
515
516 if (fstat(path_fd, ret_stat) < 0)
517 return -errno;
518
519 if (ret_path)
520 *ret_path = TAKE_PTR(p);
2b2caea2
LP
521 if (ret_fd)
522 *ret_fd = TAKE_FD(path_fd);
523
524 return 1;
525}
526
527int chase_symlinks_and_access(
528 const char *path,
529 const char *root,
530 ChaseSymlinksFlags chase_flags,
531 int access_mode,
532 char **ret_path,
533 int *ret_fd) {
534
535 _cleanup_close_ int path_fd = -1;
536 _cleanup_free_ char *p = NULL;
537 int r;
538
539 assert(path);
540
541 if (chase_flags & (CHASE_NONEXISTENT|CHASE_STEP))
542 return -EINVAL;
543
544 if (empty_or_root(root) && !ret_path && (chase_flags & (CHASE_NO_AUTOFS|CHASE_SAFE)) == 0 && !ret_fd) {
545 /* Shortcut this call if none of the special features of this call are requested */
546
547 if (faccessat(AT_FDCWD, path, access_mode, FLAGS_SET(chase_flags, CHASE_NOFOLLOW) ? AT_SYMLINK_NOFOLLOW : 0) < 0)
548 return -errno;
549
550 return 1;
551 }
552
553 r = chase_symlinks(path, root, chase_flags, ret_path ? &p : NULL, &path_fd);
554 if (r < 0)
555 return r;
556 assert(path_fd >= 0);
557
558 r = access_fd(path_fd, access_mode);
559 if (r < 0)
560 return r;
561
562 if (ret_path)
563 *ret_path = TAKE_PTR(p);
f4351959
LP
564 if (ret_fd)
565 *ret_fd = TAKE_FD(path_fd);
566
567 return 1;
568}
01bebba3
LP
569
570int chase_symlinks_and_fopen_unlocked(
571 const char *path,
572 const char *root,
8f47f880 573 ChaseSymlinksFlags chase_flags,
01bebba3
LP
574 const char *open_flags,
575 char **ret_path,
576 FILE **ret_file) {
577
578 _cleanup_free_ char *final_path = NULL;
579 _cleanup_close_ int fd = -1;
580 int mode_flags, r;
581
582 assert(path);
583 assert(open_flags);
584 assert(ret_file);
585
586 mode_flags = fopen_mode_to_flags(open_flags);
587 if (mode_flags < 0)
588 return mode_flags;
589
590 fd = chase_symlinks_and_open(path, root, chase_flags, mode_flags, ret_path ? &final_path : NULL);
591 if (fd < 0)
592 return fd;
593
594 r = take_fdopen_unlocked(&fd, open_flags, ret_file);
595 if (r < 0)
596 return r;
597
598 if (ret_path)
599 *ret_path = TAKE_PTR(final_path);
600
601 return 0;
602}