builtin/clone: abort when hardlinked source and target file differ

When performing local clones with hardlinks we refuse to copy source files which are symlinks as a mitigation for CVE-2022-39253. This check can be raced by an adversary though by changing the file to a symlink after we have checked it. Fix the issue by checking whether the hardlinked destination file matches the source file and abort in case it doesn't. This addresses CVE-2024-32021. Reported-by: Apple Product Security <product-security@apple.com> Suggested-by: Linus Torvalds <torvalds@linuxfoundation.org> Signed-off-by: Patrick Steinhardt <ps@pks.im> Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de>

Patrick Steinhardt committed Apr 15, 2024 at 13:30 UTC d1bb66a546b4bb46005d17ba711caaad26f26c1e
1 file changed +20 -1
builtin/clone.c
+20 -1
@@ -357,8 +357,27 @@ static void copy_or_link_directory(struct strbuf *src, struct strbuf *dest,
357 if (unlink(dest->buf) && errno != ENOENT)
358 die_errno(_("failed to unlink '%s'"), dest->buf);
359 if (!option_no_hardlinks) {
360 - if (!link(src->buf, dest->buf))
360 + if (!link(src->buf, dest->buf)) {
361 + struct stat st;
362 +
363 + /*
364 + * Sanity-check whether the created hardlink
365 + * actually links to the expected file now. This
366 + * catches time-of-check-time-of-use bugs in
367 + * case the source file was meanwhile swapped.
368 + */
369 + if (lstat(dest->buf, &st))
370 + die(_("hardlink cannot be checked at '%s'"), dest->buf);
371 + if (st.st_mode != iter->st.st_mode ||
372 + st.st_ino != iter->st.st_ino ||
373 + st.st_dev != iter->st.st_dev ||
374 + st.st_size != iter->st.st_size ||
375 + st.st_uid != iter->st.st_uid ||
376 + st.st_gid != iter->st.st_gid)
377 + die(_("hardlink different from source at '%s'"), dest->buf);
378 +
379 continue;
380 + }
381 if (option_local > 0)
382 die_errno(_("failed to create link '%s'"), dest->buf);
383 option_no_hardlinks = 1;