-
-
Notifications
You must be signed in to change notification settings - Fork 590
Expand file tree
/
Copy pathsyscall.c
More file actions
3990 lines (3649 loc) · 119 KB
/
Copy pathsyscall.c
File metadata and controls
3990 lines (3649 loc) · 119 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Syscall wrappers to ensure that nothing gets done in dry_run mode
* and to handle system peculiarities.
*
* Copyright (C) 1998 Andrew Tridgell
* Copyright (C) 2002 Martin Pool
* Copyright (C) 2003-2022 Wayne Davison
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, visit the http://fsf.org website.
*/
#include "rsync.h"
/* Exercise the pre-*at() portability tier on modern build hosts. */
#ifdef RSYNC_TEST_NO_AT_FDCWD
#undef AT_FDCWD
#undef AT_SYMLINK_NOFOLLOW
#undef HAVE_LINKAT
#undef HAVE_OPENAT2
#undef HAVE_UTIMENSAT
#undef O_RESOLVE_BENEATH
#endif
#if !defined MKNOD_CREATES_SOCKETS && defined HAVE_SYS_UN_H
#include <sys/un.h> /* for the socket+bind() fallback in do_mknod() */
#endif
#ifdef HAVE_SYS_ATTR_H
#include <sys/attr.h>
#endif
#if defined HAVE_SYS_FALLOCATE && !defined HAVE_FALLOCATE
#include <sys/syscall.h>
#endif
#ifdef __linux__
#include <sys/syscall.h> /* SYS_fchmodat2 / SYS_fallocate raw-syscall wrappers */
#endif
#include "ifuncs.h"
extern int dry_run;
extern int am_root;
extern int am_sender;
extern int read_only;
extern int list_only;
extern int inplace;
extern int preallocate_files;
extern int sparse_files;
extern int preserve_perms;
extern int preserve_executability;
extern int open_noatime;
extern int copy_links;
extern int copy_unsafe_links;
extern int am_daemon;
extern int am_chrooted;
extern int insecure_links;
extern int module_id;
extern unsigned int module_dirlen;
extern char *module_dir;
extern int module_dirfd; /* daemon: served module root pinned by identity, or -1 */
extern char *confine_root; /* --confine-root, or NULL; see confinement_root() */
extern unsigned int confine_rootlen;
extern char curr_dir[MAXPATHLEN]; /* defined below; fwd-declared for the seed */
extern int operator_path_resolve; /* defined below; fwd-declared for the exclude check */
#if defined AT_FDCWD && defined O_NOFOLLOW && defined O_DIRECTORY
/* Open a trusted absolute anchor directory as an owned dirfd. When the anchor is
* the served module root and the daemon pinned it by identity (module_dirfd), dup
* that fd rather than re-resolving the absolute path with openat(AT_FDCWD, ...) --
* which re-traverses the module's ancestors as the dropped-privilege module uid
* and EACCESes when the module sits under a non-traversable parent (a 0700 home).
* Functionally identical (same inode), just privilege-drop-safe. Gated like its
* callers (the secure resolver and dpc_dir_fd both require these three). */
static int open_anchor_dirfd(const char *path)
{
if (module_dirfd >= 0 && am_daemon && module_dir && strcmp(path, module_dir) == 0)
return dup(module_dirfd);
return openat(AT_FDCWD, path, O_RDONLY | O_DIRECTORY);
}
#endif
/* Single gate for whether path resolution must be hardened against
* parent-component symlink races (TOCTOU). Used by the do_*_at()/do_*_atfd()
* wrappers and the receiver's secure-open/secure-mkstemp choices. Hardens
* every non-chrooted receiver (a chroot is its own confinement); the sender is
* excluded so it still follows -L/--copy-links symlinks. A daemon chroot with
* an inner-module /./ boundary still needs these checks because the kernel
* chroot confines the outer path, not the inner module. */
int secure_relpath_active(void)
{
/* The "insecure links" / --insecure-links opt-out restores the legacy
* follow-any-symlink behaviour uniformly, so it disables the secure
* resolver on the RECEIVER side too (not just the sender enumeration that
* already checks symlink_optout_allowed()). Without this an opted-out
* module still confined receiver writes/stats through a pre-existing
* in-module symlink -- failing to match the pre-3.4.3 behaviour the opt-out
* promises (documented in rsyncd.conf(5) "munge symlinks"/"insecure links"). */
if (symlink_optout_allowed())
return 0;
if (am_daemon && am_chrooted && module_dirlen)
return 1;
return !am_chrooted && (am_daemon || !am_sender);
}
/* Whether the operator-supplied-path symlink confinement is opted out. For a
* non-daemon transfer this is the local --insecure-links flag. For a daemon it
* is governed ONLY by the module's "insecure links" config (lp_insecure_links)
* -- never by a peer-supplied --insecure-links (a client cannot disable a
* daemon's confinement; the daemon also drops a connection that sends it). So a
* forwarded flag is structurally inert here. */
int symlink_optout_allowed(void)
{
if (am_daemon)
return module_id >= 0 && lp_insecure_links(module_id);
return insecure_links;
}
/* The root an operator/peer-supplied path must stay under, or NULL when nothing
* is confined. A daemon has the served module; a server launched by a wrapper
* with its own restricted directory (rrsync) gets one from --confine-root.
*
* A daemon never honours --confine-root: module_dir is the boundary there, and
* the option arrives in a peer-supplied argv, so obeying it could only loosen
* the module. */
static const char *confinement_root(unsigned int *lenp)
{
if (am_daemon) {
*lenp = module_dirlen;
return module_dir;
}
*lenp = confine_rootlen;
return confine_root;
}
/* Split a recognised fd-pin prefix off `p`, returning the tail -- "" for the
* pin directory itself, otherwise a string starting with '/'. NULL when `p`
* is not in an fd-pin namespace. */
static const char *fd_pin_tail(const char *p)
{
const char *s;
if (strncmp(p, "/dev/fd", 7) == 0) {
s = p + 7;
return (*s == '\0' || *s == '/') ? s : NULL;
}
if (strncmp(p, "/proc/", 6) != 0)
return NULL;
s = p + 6;
if (strncmp(s, "self/", 5) == 0) /* "/proc/self/..." */
s += 4;
else { /* "/proc/<pid>/..." */
const char *d = s;
while (*s >= '0' && *s <= '9')
s++;
if (s == d || *s != '/')
return NULL;
}
if (strncmp(s, "/fd", 3) != 0)
return NULL;
s += 3;
return (*s == '\0' || *s == '/') ? s : NULL;
}
/* An EXACT pin entry, such as "/proc/self/fd/7" or "/dev/fd/7", whose target is
* what confinement must judge. rrsync also writes a pinned parent as
* ".../fd/7/<leaf>", but the walk resolves the magic link itself and checks the
* components past it, so only the bare entry is resolved here. Requiring all
* digits keeps a planted name like ".../fd/outside-secret" out. */
static int is_exact_fd_pin(const char *p)
{
const char *tail = fd_pin_tail(p);
if (!tail || *tail != '/')
return 0;
for (++tail; *tail >= '0' && *tail <= '9'; tail++) {}
return *tail == '\0' && tail[-1] != '/';
}
/* Refuse (return 1) when the ABSOLUTE resolved path `abspath` lands OUTSIDE the
* confinement root, for an operator/peer-supplied path that must stay inside it
* (--partial-dir/--backup-dir/alt-basis/merge files: operator_path_resolve). An
* in-tree symlink owned by uid 0 / the euid is followed by design, so it can
* redirect the resolved target outside the root; this catches that escape.
*
* This is ROOT confinement only. The daemon exclude/filter list is a name-based
* visibility filter, NOT a physical-path boundary: a symlink whose own name is
* not excluded may still resolve into an excluded IN-tree subtree, exactly as in
* stock rsync. The defense for a writable module is `munge symlinks` (see
* rsyncd.conf(5)), not this walk. */
static int abspath_outside_confinement(const char *abspath)
{
unsigned int rootlen;
const char *root = confinement_root(&rootlen);
char pinned[MAXPATHLEN];
if (!root || !abspath)
return 0;
if (rootlen <= 1) /* root is "/": nothing is outside */
return 0;
/* An fd pin (rrsync rewrites a validated option path to /proc/self/fd/N so
* no later symlink can redirect it) is spelled outside the root by
* construction. Judge it by what it points AT rather than by its spelling,
* so a pin is neither wrongly refused nor blindly trusted. A pin we cannot
* resolve to an absolute path is refused, not waved through: an unreadable
* pin is exactly the case where we cannot say where the open would land. */
if (!am_daemon) {
const char *tail = fd_pin_tail(abspath);
if (tail && !*tail)
return 0; /* the pin directory: transit, opens nothing */
if (is_exact_fd_pin(abspath)) {
ssize_t n = readlink(abspath, pinned, sizeof pinned - 1);
if (n <= 0 || pinned[0] != '/')
return operator_path_resolve ? 1 : 0;
pinned[n] = '\0';
abspath = pinned;
}
}
if (strncmp(abspath, root, rootlen) == 0
&& (abspath[rootlen] == '\0' || abspath[rootlen] == '/'))
return 0; /* inside: name-based exclude is not a boundary */
/* Not under the root. An ABSOLUTE walk passes through the root's ancestors
* ("/", "/home", ...) on the way down -- those are not "outside", just
* not-yet-arrived, so allow them. A path that has truly DIVERGED is
* outside: refuse it for an operator/peer path that must stay in the tree
* (operator_path_resolve); other opens (--log-file, --*-from, lock/motd)
* may legitimately live elsewhere. The --insecure-links / "insecure links
* = yes" opt-out short-circuits before we get here. */
size_t alen = strlen(abspath);
if (alen == 0
|| (strncmp(abspath, root, alen) == 0 && root[alen] == '/'))
return 0; /* ancestor of the root: still descending */
return operator_path_resolve ? 1 : 0;
}
/* Advance the tracked absolute path `abspath` by one resolved component,
* normalizing "." and ".." exactly as openat() does so the module-confinement
* check (abspath_outside_confinement) sees the REAL resolved target. -1/
* ENAMETOOLONG on overflow. */
static int abspath_step(char *abspath, size_t cap, const char *comp, size_t comp_len)
{
if (comp_len == 1 && comp[0] == '.')
return 0; /* "." -- no movement */
if (comp_len == 2 && comp[0] == '.' && comp[1] == '.') {
char *s = strrchr(abspath, '/'); /* ".." -- pop a component */
if (s)
*s = '\0';
else
abspath[0] = '\0';
return 0;
}
size_t al = strlen(abspath);
size_t off = (al > 0 && abspath[al-1] == '/') ? al : al + 1; /* no "//" */
if (off + comp_len >= cap) {
errno = ENAMETOOLONG;
return -1;
}
if (off != al)
abspath[al] = '/';
memcpy(abspath + off, comp, comp_len + 1);
return 0;
}
/* Open an operator-supplied path, refusing to traverse any symlink (parent or
* leaf) not owned by uid 0 or our euid. A trusted-owned symlink (e.g. root's
* /var/log -> /data/log) is still followed; an untrusted one fails ELOOP.
* Unlike plain O_NOFOLLOW this also defends a planted parent component
* (--log-file=$plant/log), not just a planted leaf. Used for opens that may
* transit attacker-writable parents: --log-file, --password-file, --*-from,
* --read/write-batch, daemon motd/lock/early-input/--config.
*
* Walks component-by-component with fstatat(AT_SYMLINK_NOFOLLOW) +
* openat(O_NOFOLLOW), splicing a trusted symlink's target back into the path.
* Returns the fd, or -1 (errno ELOOP on the security refusal so callers can
* tell it apart). Falls back to plain open() where openat/O_NOFOLLOW are
* unavailable. */
/* Core walk. When out_abs is non-NULL and the path resolves to a directory
* (O_DIRECTORY), the resolved absolute path is copied there -- owner_walk_parent
* uses it to filter-check the (otherwise unchecked) leaf basename. */
static int ona_open(const char *path, int flags, mode_t mode, char *out_abs, size_t out_cap)
{
#if defined AT_FDCWD && defined O_NOFOLLOW
/* O_CLOEXEC predates some still-supported targets; mirror rand_bytes()'s
* fallback in syscall.c so a build without it still compiles. */
#ifndef O_CLOEXEC
#define O_CLOEXEC 0
#endif
#ifdef O_PATH
const int dir_traverse_flags = O_PATH | O_DIRECTORY | O_CLOEXEC;
#else
const int dir_traverse_flags = O_RDONLY | O_DIRECTORY | O_CLOEXEC;
#endif
if (!path || !*path) {
errno = EINVAL;
return -1;
}
/* Opted out (local --insecure-links, or a daemon module with "insecure
* links = yes"): restore the legacy symlink-following open. */
if (symlink_optout_allowed())
return open(path, flags, mode);
const uid_t trusted_uid = geteuid();
int dfd = AT_FDCWD;
int dfd_owns = 0;
/* Absolute path of the current dir, for the confinement refusal
* (abspath_outside_confinement). A relative operator path starts at the
* daemon's cwd == the module root; an absolute one (or a followed absolute
* symlink target) restarts at "/". */
char abspath[MAXPATHLEN];
abspath[0] = '\0';
if (am_daemon && module_dir && module_dir[0] == '/')
strlcpy(abspath, module_dir, sizeof abspath); /* "/" for a path=/ module */
else if (confine_root) {
/* Unlike a daemon's, this cwd is not pinned to the root -- the receiver
* chdir's into the destination -- so it has to be read, not assumed.
* It must be the PHYSICAL cwd: curr_dir is the lexical name change_dir()
* was given, so after descending a trusted symlink the tracker sits at a
* different depth than the kernel, and a ".." that really escapes looks
* like it landed inside.
*
* Without it there is nothing to measure against, and an empty tracker
* does NOT deny by itself -- a leading ".." pops nothing and an empty
* path reads as an ancestor of the root -- so refuse the open instead. */
if (!getcwd(abspath, sizeof abspath))
return -1;
}
/* An fd pin (rrsync rewrites an option path to /proc/self/fd/N so no
* later symlink can redirect it) is spelled outside the root by
* construction, so the walk has to be allowed through /proc/self/fd to
* reach the magic link. This only suspends the check for that prefix:
* following the link restarts the walk at its absolute target, and every
* component of THAT is checked, so a pin aimed outside is still refused. */
int pin_transit = !am_daemon && confine_root && fd_pin_tail(path) != NULL;
/* Path-walk state. `remaining` is the unconsumed tail; we splice
* symlink targets back into it as we go. Sized 2x MAXPATHLEN so a
* one-level expansion can't immediately overflow; deeper chains
* fail with ENAMETOOLONG below. */
char remaining[MAXPATHLEN * 2];
if (strlcpy(remaining, path, sizeof remaining) >= sizeof remaining) {
errno = ENAMETOOLONG;
return -1;
}
/* Absolute path: pin "/" as the starting dfd. */
if (remaining[0] == '/') {
dfd = open("/", dir_traverse_flags);
if (dfd < 0)
return -1;
dfd_owns = 1;
abspath[0] = '\0'; /* now resolving from "/" */
char *p = remaining;
while (*p == '/') p++;
memmove(remaining, p, strlen(p) + 1);
}
int loops = 40; /* SYMLOOP_MAX-ish; breaks symlink cycles. Counts symlink
* expansions only (below), NOT path depth -- a deep but
* symlink-free path must resolve, not ELOOP. */
int retfd = -1;
int saved_errno = 0;
while (*remaining) {
/* Peel one component off the front of `remaining`. */
char *slash = strchr(remaining, '/');
size_t comp_len = slash ? (size_t)(slash - remaining) : strlen(remaining);
char comp[MAXPATHLEN];
if (comp_len == 0 || comp_len >= sizeof comp) {
saved_errno = comp_len == 0 ? EINVAL : ENAMETOOLONG;
goto out;
}
memcpy(comp, remaining, comp_len);
comp[comp_len] = '\0';
int is_last = (slash == NULL);
/* Inspect this component without following symlinks. */
STRUCT_STAT lst;
if (fstatat(dfd, comp, &lst, AT_SYMLINK_NOFOLLOW) < 0) {
/* The leaf may not exist yet (O_CREAT case). Allow it
* and openat with O_NOFOLLOW so a race-planted leaf
* symlink at this instant is still refused. */
if (is_last && errno == ENOENT && (flags & O_CREAT)) {
if (abspath_step(abspath, sizeof abspath, comp, comp_len) < 0) {
saved_errno = errno;
goto out;
}
if (!pin_transit && abspath_outside_confinement(abspath)) {
saved_errno = ELOOP;
goto out;
}
retfd = openat(dfd, comp, flags | O_NOFOLLOW, mode);
saved_errno = errno;
goto out;
}
saved_errno = errno;
goto out;
}
if (S_ISLNK(lst.st_mode)) {
/* Symlink: untrusted owner is refused; trusted owner is followed
* via readlinkat + splice. In a user namespace the /proc/self and
* /dev/fd symlinks may report the overflow uid, so
* allow those exact components while traversing a recognised pin. */
int namespace_pin = pin_transit
&& ((strcmp(abspath, "/proc") == 0 && strcmp(comp, "self") == 0)
|| (strcmp(abspath, "/dev") == 0 && strcmp(comp, "fd") == 0));
if (!namespace_pin && lst.st_uid != 0 && lst.st_uid != trusted_uid) {
saved_errno = ELOOP;
goto out;
}
if (--loops < 0) { /* cap symlink-follow chains */
saved_errno = ELOOP;
goto out;
}
char target[MAXPATHLEN];
ssize_t n = readlinkat(dfd, comp, target, sizeof target - 1);
if (n < 0) {
saved_errno = errno;
goto out;
}
target[n] = '\0';
/* Splice: new `remaining` = <target> + <tail-after-comp>.
* Absolute target restarts the walk from "/". */
char tail[MAXPATHLEN];
tail[0] = '\0';
if (slash)
strlcpy(tail, slash, sizeof tail);
char rebuilt[MAXPATHLEN * 2];
if (snprintf(rebuilt, sizeof rebuilt, "%s%s",
target, tail) >= (int)sizeof rebuilt) {
saved_errno = ENAMETOOLONG;
goto out;
}
if (target[0] == '/') {
if (dfd_owns) close(dfd);
dfd = open("/", dir_traverse_flags);
if (dfd < 0) {
saved_errno = errno;
dfd_owns = 0;
goto out;
}
dfd_owns = 1;
abspath[0] = '\0'; /* followed an absolute target: restart from "/" */
/* "self" resolves to "<pid>", still inside the pin;
* the magic link itself lands elsewhere and ends the
* exemption. Never turns back on. */
pin_transit = pin_transit && fd_pin_tail(rebuilt) != NULL;
char *p = rebuilt;
while (*p == '/') p++;
strlcpy(remaining, p, sizeof remaining);
} else {
strlcpy(remaining, rebuilt, sizeof remaining);
}
continue;
}
/* Non-symlink. */
if (is_last) {
if (abspath_step(abspath, sizeof abspath, comp, comp_len) < 0) {
saved_errno = errno;
goto out;
}
if (!pin_transit && abspath_outside_confinement(abspath)) {
saved_errno = ELOOP;
goto out;
}
retfd = openat(dfd, comp, flags | O_NOFOLLOW, mode);
saved_errno = errno;
/* Resolved leaf dir (O_DIRECTORY): hand its path back so
* owner_walk_parent can filter-check the operation's leaf. */
if (retfd >= 0 && out_abs && out_cap)
/* Root-resolved (".." popped abspath empty) tracked daemon walk:
* hand back "/" so owner_walk_parent still leaf-checks (path=/ bypass). */
strlcpy(out_abs, (am_daemon && !abspath[0]) ? "/" : abspath, out_cap);
goto out;
}
if (!S_ISDIR(lst.st_mode)) {
saved_errno = ENOTDIR;
goto out;
}
/* track the resolved path so a target outside the module is refused */
if (abspath_step(abspath, sizeof abspath, comp, comp_len) < 0) {
saved_errno = errno;
goto out;
}
if (!pin_transit && abspath_outside_confinement(abspath)) {
saved_errno = ELOOP;
goto out;
}
int next = openat(dfd, comp, dir_traverse_flags | O_NOFOLLOW);
if (next < 0) {
saved_errno = errno;
goto out;
}
if (dfd_owns) close(dfd);
dfd = next;
dfd_owns = 1;
/* Advance `remaining` past this component (and the slash). */
if (slash) {
char *p = slash;
while (*p == '/') p++;
memmove(remaining, p, strlen(p) + 1);
} else {
remaining[0] = '\0';
}
}
/* Path resolved entirely to a directory (no leaf component left).
* Reopen the held traversal fd with the caller's requested access mode;
* an O_PATH fd is sufficient for traversal and fchdir but not operations
* such as fchmod. */
if (flags & O_DIRECTORY) {
retfd = openat(dfd, ".", flags | O_NOFOLLOW, mode);
saved_errno = retfd < 0 ? errno : 0;
if (out_abs && out_cap)
/* Root-resolved (".." popped abspath empty) tracked daemon walk:
* hand back "/" so owner_walk_parent still leaf-checks (path=/ bypass). */
strlcpy(out_abs, (am_daemon && !abspath[0]) ? "/" : abspath, out_cap);
} else {
saved_errno = EISDIR;
}
out:
if (dfd_owns) close(dfd);
errno = saved_errno;
return retfd;
#else
/* Pre-AT_FDCWD / no O_NOFOLLOW systems: best-effort fallback. */
(void)out_abs; (void)out_cap;
return open(path, flags, mode);
#endif
}
int open_no_attacker_symlinks(const char *path, int flags, mode_t mode)
{
return ona_open(path, flags, mode, NULL, 0);
}
/* When set, the do_*_at() wrappers resolve their path as an OPERATOR-supplied
* directory path (an absolute or relative --backup-dir/--temp-dir/--*-dest)
* using the ownership walk -- follow a symlink owned by uid 0 or our euid,
* refuse any other-uid one, at every component -- instead of the stricter
* transfer-path resolver (which refuses all symlinks and is confined beneath the
* transfer root). An operator path may legitimately point outside the tree, so
* the trust signal is authority (ownership), not location. Set around the
* relevant ops by backup.c et al.; the opt-out (--insecure-links / "insecure
* links =") restores legacy following. Default 0 (transfer-path resolver). */
int operator_path_resolve = 0;
#if defined AT_FDCWD && defined O_NOFOLLOW && defined O_DIRECTORY
/* For an operator-supplied path: open its parent directory via the ownership
* walk (handles absolute and relative paths) and point *bname at the final
* component. Returns the dirfd (caller closes) or -1 with errno set. */
int owner_walk_parent(const char *path, const char **bname)
{
const char *slash = strrchr(path, '/');
char dir[MAXPATHLEN], pabs[MAXPATHLEN];
size_t dlen;
int dfd;
*bname = slash ? slash + 1 : path;
pabs[0] = '\0';
if (!slash)
dfd = ona_open(".", O_RDONLY | O_DIRECTORY, 0, pabs, sizeof pabs);
else {
dlen = slash == path ? 1 : (size_t)(slash - path); /* "/x" -> parent "/" */
if (dlen >= sizeof dir) {
errno = ENAMETOOLONG;
return -1;
}
memcpy(dir, path, dlen);
dir[dlen] = '\0';
dfd = ona_open(dir, O_RDONLY | O_DIRECTORY, 0, pabs, sizeof pabs);
}
if (dfd < 0)
return -1;
/* owner_walk only resolved the PARENT; check the resolved leaf too, so a
* symlinked operator path cannot act on a leaf that resolves OUTSIDE the
* module in an otherwise-served dir. (The module exclude/filter is name-
* based and not enforced here -- see abspath_outside_confinement.) */
if (pabs[0]) {
char leafabs[MAXPATHLEN];
if (snprintf(leafabs, sizeof leafabs, "%s/%s", pabs, *bname) >= (int)sizeof leafabs) {
close(dfd);
errno = ENAMETOOLONG; /* fail closed, never skip the check */
return -1;
}
if (abspath_outside_confinement(leafabs)) {
close(dfd);
errno = ELOOP;
return -1;
}
}
return dfd;
}
#endif
#ifndef S_BLKSIZE
# if defined hpux || defined __hpux__ || defined __hpux
# define S_BLKSIZE 1024
# elif defined _AIX && defined _I386
# define S_BLKSIZE 4096
# else
# define S_BLKSIZE 512
# endif
#endif
#ifdef SUPPORT_CRTIMES
#ifdef HAVE_GETATTRLIST
#pragma pack(push, 4)
struct create_time {
uint32 length;
struct timespec crtime;
};
#pragma pack(pop)
#elif defined __CYGWIN__
#include <windows.h>
#endif
#endif
#define RETURN_ERROR_IF(x,e) \
do { \
if (x) { \
errno = (e); \
return -1; \
} \
} while (0)
#define RETURN_ERROR_IF_RO_OR_LO RETURN_ERROR_IF(read_only || list_only, EROFS)
/* A NULL path reaching one of the path-forwarding wrappers below is always a
* caller bug; reject it rather than forwarding NULL to libc. Also quiets the
* static analyzer's interprocedural nonnull false positives. */
#define RETURN_ERROR_IF_NULL(p) RETURN_ERROR_IF(!(p), EFAULT)
int do_unlink(const char *path)
{
if (dry_run) return 0;
RETURN_ERROR_IF_RO_OR_LO;
return unlink(path);
}
/*
Symlink-race-safe variant of do_unlink() for receiver-side use. See
the comment on do_chmod_at() for the threat model. unlink() resolves
parent components, so a parent-symlink swap can delete an outside
file under the daemon's authority. Defence: open the parent of path
under secure_relative_open() and use unlinkat() (flags=0) against
that dirfd.
Falls through to do_unlink() for the same dry-run / non-daemon /
chrooted / no-parent / absolute-path cases as the other wrappers.
*/
int do_unlink_at(const char *path)
{
#ifdef AT_FDCWD
extern int am_daemon, am_chrooted;
char dirpath[MAXPATHLEN];
const char *bname;
const char *slash;
int dfd, ret, e;
size_t dlen;
if (dry_run) return 0;
RETURN_ERROR_IF_RO_OR_LO;
RETURN_ERROR_IF_NULL(path);
#if defined O_NOFOLLOW && defined O_DIRECTORY
if (operator_path_resolve) {
if (symlink_optout_allowed())
return unlink(path);
dfd = owner_walk_parent(path, &bname);
if (dfd < 0)
return -1;
ret = unlinkat(dfd, bname, 0);
e = errno;
close(dfd);
errno = e;
return ret;
}
#endif
if (!secure_relpath_active())
return unlink(path);
if (!path || !*path || *path == '/')
return unlink(path);
slash = strrchr(path, '/');
if (!slash)
return unlink(path);
dlen = slash - path;
if (dlen >= sizeof dirpath) {
errno = ENAMETOOLONG;
return -1;
}
memcpy(dirpath, path, dlen);
dirpath[dlen] = '\0';
bname = slash + 1;
dfd = secure_relative_open(NULL, dirpath, O_RDONLY | O_DIRECTORY, 0);
if (dfd < 0)
return -1;
ret = unlinkat(dfd, bname, 0);
e = errno;
close(dfd);
errno = e;
return ret;
#else
return do_unlink(path);
#endif
}
#ifdef SUPPORT_LINKS
int do_symlink(const char *lnk, const char *path)
{
if (dry_run) return 0;
RETURN_ERROR_IF_RO_OR_LO;
RETURN_ERROR_IF_NULL(lnk);
RETURN_ERROR_IF_NULL(path);
#if defined NO_SYMLINK_XATTRS || defined NO_SYMLINK_USER_XATTRS
/* For --fake-super, we create a normal file with mode 0600
* and write the lnk into it. */
if (am_root < 0) {
int ok, len = strlen(lnk);
int fd = open(path, O_WRONLY|O_CREAT|O_TRUNC, S_IWUSR|S_IRUSR);
if (fd < 0)
return -1;
ok = write(fd, lnk, len) == len;
if (close(fd) < 0)
ok = 0;
return ok ? 0 : -1;
}
#endif
return symlink(lnk, path);
}
/*
Symlink-race-safe variant of do_symlink() for receiver-side use. See
the comment on do_chmod_at() for the threat model. For a real symlink
only the parent directory of `path` needs protection -- symlinkat()
does not resolve the final component (it creates it). Defence: open
the parent of `path` under secure_relative_open() and call symlinkat()
against that dirfd; a top-level (no-slash) path has no parent to
confine, so it uses AT_FDCWD directly. The link target string `lnk` is
stored verbatim and not resolved at creation time, so it doesn't need
scrutiny here.
For --fake-super (am_root < 0) the "symlink" is written as a regular
file, so the final component IS resolved at creation: we create it
with openat(... O_NOFOLLOW) so a pre-planted symlink at the basename
cannot redirect the write outside the module. This protection applies
to top-level paths too -- the previous code fell through to the
bare-path do_symlink() there, whose plain open() followed such a
symlink.
*/
int do_symlink_at(const char *lnk, const char *path)
{
#ifdef AT_FDCWD
extern int am_daemon, am_chrooted;
char dirpath[MAXPATHLEN];
const char *bname;
const char *slash;
int dfd = AT_FDCWD, ret, e;
BOOL owns = False;
size_t dlen;
if (dry_run) return 0;
RETURN_ERROR_IF_RO_OR_LO;
#if defined O_NOFOLLOW && defined O_DIRECTORY
if (operator_path_resolve) {
/* Operator path (e.g. an absolute --backup-dir): confine the
* parent with the ownership walk, then fall through to the shared
* leaf-creation below so fake-super emulation is preserved. */
if (symlink_optout_allowed())
return do_symlink(lnk, path);
dfd = owner_walk_parent(path, &bname);
if (dfd < 0)
return -1;
owns = True;
} else
#endif
{
if (!secure_relpath_active())
return do_symlink(lnk, path);
if (!path || !*path || *path == '/')
return do_symlink(lnk, path);
/* A path with a slash needs secure_relative_open to confine its
* parent; a top-level path is in CWD (AT_FDCWD), no parent to
* subvert. The leaf is protected below either way (symlinkat()
* won't follow it; the fake-super openat() uses O_NOFOLLOW). */
slash = strrchr(path, '/');
if (slash) {
dlen = slash - path;
if (dlen >= sizeof dirpath) {
errno = ENAMETOOLONG;
return -1;
}
memcpy(dirpath, path, dlen);
dirpath[dlen] = '\0';
bname = slash + 1;
dfd = secure_relative_open(NULL, dirpath, O_RDONLY | O_DIRECTORY, 0);
if (dfd < 0)
return -1;
owns = True;
} else {
bname = path;
}
}
#if defined NO_SYMLINK_XATTRS || defined NO_SYMLINK_USER_XATTRS
/* For --fake-super, do_symlink writes the link target into a
* regular file rather than creating a real symlink. Do that here
* against the (secure or AT_FDCWD) dirfd, with O_NOFOLLOW so a pre-
* planted symlink at the basename can't redirect the file creation. */
if (am_root < 0) {
int len = strlen(lnk);
int fd = openat(dfd, bname,
O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW,
S_IWUSR | S_IRUSR);
if (fd < 0) {
e = errno;
if (owns) close(dfd);
errno = e;
return -1;
}
ret = (write(fd, lnk, len) == len) ? 0 : -1;
if (close(fd) < 0)
ret = -1;
e = errno;
if (owns) close(dfd);
errno = e;
return ret;
}
#endif
ret = symlinkat(lnk, dfd, bname);
e = errno;
if (owns) close(dfd);
errno = e;
return ret;
#else
return do_symlink(lnk, path);
#endif
}
/* NOFOLLOW_HIT_SYMLINK() lives in rsync.h (shared with util1.c's change_dir). */
#if defined NO_SYMLINK_XATTRS || defined NO_SYMLINK_USER_XATTRS
ssize_t do_readlink(const char *path, char *buf, size_t bufsiz)
{
/* For --fake-super, we read the link from the file. */
if (am_root < 0) {
int fd = do_open_nofollow(path, O_RDONLY);
if (fd >= 0) {
int len = read(fd, buf, bufsiz);
close(fd);
return len;
}
if (!NOFOLLOW_HIT_SYMLINK(errno))
return -1;
/* A real symlink needs to be turned into a fake one on the receiving
* side, so tell the generator that the link has no length. */
if (!am_sender)
return 0;
/* Otherwise fall through and let the sender report the real length. */
}
return readlink(path, buf, bufsiz);
}
#endif
ssize_t do_readlink_atfd(int dfd, const char *name, char *buf, size_t bufsiz)
{
#ifdef AT_FDCWD
# if defined NO_SYMLINK_XATTRS || defined NO_SYMLINK_USER_XATTRS
if (am_root < 0) {
int fd = openat(dfd, name, O_RDONLY | O_NOFOLLOW);
if (fd >= 0) {
int len = read(fd, buf, bufsiz);
close(fd);
return len;
}
if (!NOFOLLOW_HIT_SYMLINK(errno))
return -1;
if (!am_sender)
return 0;
}
# endif
return readlinkat(dfd, name, buf, bufsiz);
#else
(void)dfd;
return do_readlink(name, buf, bufsiz);
#endif
}
#endif
#if defined HAVE_LINK || defined HAVE_LINKAT
int do_link(const char *old_path, const char *new_path)
{
if (dry_run) return 0;
RETURN_ERROR_IF_RO_OR_LO;
RETURN_ERROR_IF_NULL(old_path);
RETURN_ERROR_IF_NULL(new_path);
#ifdef HAVE_LINKAT
return linkat(AT_FDCWD, old_path, AT_FDCWD, new_path, 0);
#else
return link(old_path, new_path);
#endif
}
/*
Symlink-race-safe variant of do_link() for receiver-side use. See
the comment on do_chmod_at() for the threat model. link() resolves
parent components of *both* old_path and new_path, so a parent-
symlink swap on either side can plant the new hard link outside
the module, or hard-link an outside file into the module (read
disclosure).
Defence: open each parent under secure_relative_open() and use
linkat() between the two dirfds, reusing one when the parents
match. flags=0 matches the existing do_link() (don't follow a
symbolic-link old_path). Only available on systems with linkat();
pre-AT_FDCWD systems fall through to do_link().
*/
int do_link_at(const char *old_path, const char *new_path)
{
#if defined AT_FDCWD && defined HAVE_LINKAT
extern int am_daemon, am_chrooted;
char old_dirpath[MAXPATHLEN], new_dirpath[MAXPATHLEN];
const char *old_bname, *new_bname;
const char *old_slash, *new_slash;
int old_dfd = AT_FDCWD, new_dfd = AT_FDCWD;
BOOL old_owns = False, new_owns = False;
int ret, e;
size_t old_dlen = 0, new_dlen = 0;
if (dry_run) return 0;
RETURN_ERROR_IF_RO_OR_LO;
if (!secure_relpath_active())
return do_link(old_path, new_path);
if (!old_path || !*old_path || !new_path || !*new_path)
return do_link(old_path, new_path);
#if defined O_NOFOLLOW && defined O_DIRECTORY
/* Operator-supplied path (a --backup-dir/--link-dest side): resolve each
* parent via the ownership walk (follow uid0/euid symlinks, refuse others). */
if (operator_path_resolve) {
if (symlink_optout_allowed())
return do_link(old_path, new_path);
old_dfd = owner_walk_parent(old_path, &old_bname);
if (old_dfd < 0)
return -1;
new_dfd = owner_walk_parent(new_path, &new_bname);
if (new_dfd < 0) {
e = errno;
close(old_dfd);
errno = e;
return -1;
}
ret = linkat(old_dfd, old_bname, new_dfd, new_bname, 0);
e = errno;
close(new_dfd);
close(old_dfd);
errno = e;
return ret;
}
#endif
old_slash = strrchr(old_path, '/');
new_slash = strrchr(new_path, '/');