Skip to content

Commit 0a2e7af

Browse files
[3.15] gh-149835: Use realpath() instead of abspath() in shutil.move() (GH-149986) (GH-151009)
(cherry picked from commit fab449b) Co-authored-by: Thomas Kowalski <thom.kowa@gmail.com>
1 parent 934ae3e commit 0a2e7af

3 files changed

Lines changed: 22 additions & 2 deletions

File tree

Lib/shutil.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -940,8 +940,8 @@ def move(src, dst, copy_function=copy2):
940940
return real_dst
941941

942942
def _destinsrc(src, dst):
943-
src = os.path.abspath(src)
944-
dst = os.path.abspath(dst)
943+
src = os.path.realpath(src)
944+
dst = os.path.realpath(dst)
945945
if not src.endswith(os.path.sep):
946946
src += os.path.sep
947947
if not dst.endswith(os.path.sep):

Lib/test/test_shutil.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2914,6 +2914,23 @@ def test_destinsrc_false_positive(self):
29142914
finally:
29152915
os_helper.rmtree(TESTFN)
29162916

2917+
@os_helper.skip_unless_symlink
2918+
def test_destinsrc_symlink_bypass(self):
2919+
tmp = self.mkdtemp()
2920+
src = os.path.join(tmp, 'src')
2921+
os.makedirs(src)
2922+
# tmp/link -> tmp (one level up)
2923+
link = os.path.join(tmp, 'link')
2924+
os.symlink(tmp, link)
2925+
# raw path: tmp/link/src/sub - no src prefix in string space
2926+
# real path: tmp/src/sub - physically inside src
2927+
dst = os.path.join(link, 'src', 'sub')
2928+
self.assertTrue(
2929+
shutil._destinsrc(src, dst),
2930+
msg='_destinsrc failed to detect dst inside src via symlink '
2931+
'(dst=%s, src=%s)' % (dst, src),
2932+
)
2933+
29172934
@os_helper.skip_unless_symlink
29182935
@mock_rename
29192936
def test_move_file_symlink(self):
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
:func:`shutil.move` now resolves symlinks via :func:`os.path.realpath`
2+
when checking whether the destination is inside the source directory,
3+
preventing a symlink-based bypass of that guard.

0 commit comments

Comments
 (0)