В ядре Linux была устранена следующая уязвимость: fs: don't sequently unmount busy mounts The propagate_mount_busy() helper существует, чтобы решить, может ли быть достигнута синхронность. Он делает это, глядя на копии жертв в горах, на которых распространяется его родитель. Одна из этих функций от распространения ада.
Он пропускает копию, которая имеет дочернее монтирование, за исключением случая одного дочернего монтирования, покрывающего корень копии. Раньше этот алгоритм был точным. Это больше не так.
Первоначально во время размножения были размонтированы только бездетные копии. И 1064f874abc0 («mnt: Tuck монтируется под другими вместо создания теневых / боковых креплений.») в итоге добавил покрытые крепления к обеим сторонам за один раз. Появился 99b19d16471e («mnt: In propgate_umount handle visiting mounts in any order»), который начал демонтироваться больше, чем раньше: [1]: копия монтируется, когда каждый из его детей является либо его перебором, либо копией самой жертвы.
В первом случае перебор производится повторно. В последнем случае копия жертвы будет демонтирована. Таким образом, propagate_umount() был переписан без корректировки propagate_mount_busy().
И в настоящее время propagate_mount_busy() не смотрит на копии жертвы, у которой есть два или более детей, или один ребенок, который не является перебором. Таким образом, любая такая копия в [1] не проверяется на наличие ссылок. В результате получается синхронное размонтирование, вытаскивающее крепление, которое все еще используется.
Контейнер может столкнуться с этим со своими собственными креплениями. Хост делит дерево с контейнером, а хост имеет монт в этом дереве: mount -t tmpfs none /mnt mount --make-shared /mnt mount -t tmpfs no /mnt/a Контейнер /mnt является рабом mount. The container now takes a detached copy of the tree and mounts that copy beneath its propagated copy of /mnt/a and keeps the file descriptor to the tree open: unshare -m --propagation unchanged mount --make-rslave / fd = open_tree(AT_FDCWD, "/mnt", OPEN_TREE_CLONE | AT_RECURSIVE) move_mount(fd, "", AT_FDCWD, "/mnt/a", MOVE_MOUNT_BENEATH) grep /mnt /proc/self/mountinfo 775 355 ... /mnt ... master:646 777 775 ... /mnt/a ... master:646 776 777 ... /mnt/a ... master:647 778 777 ... /mnt/a/a ... master:647 The now attached tree (777) is now mounted beneath the container's copy of /mnt/a.
Это также место, где находится монтирование хоста (как видно из пространства имен хоста). Таким образом, размноженная копия (776) крепления хоста находится поверх его корня, а копия этого (778) находится внутри него. Теперь хост работает: umount /mnt/a и это удается.
Перемещенное дерево и копия внутри него исчезли из контейнера. Теперь осталась только распространяемая копия, и она была возвращена туда, где она была раньше: grep /mnt /proc/self/mountinfo 775 355 ... /mnt ... master: 646 776 775 ... /mnt / a ... Но дескриптор файла по-прежнему ссылается на перемещенное дерево.
Таким образом, синхронный монтаж отсоединил крепление, которое все еще используется. Учите propagate_mount_busy() тем же проверкам, что и propagate_umount(). Теперь он проверяет одно крепление жертвы без детей, для которого он может предположить, что MNT_LOCKED очищен от каждой копии, как и propagate_umount ().
Копии образуют цепочки. IOW, когда копия сама получает распространение от родителя жертвы, то монтирование в той же точке монтирования внутри этой копии также является копией. Получает ли крепление распространение от жертвы, можно просто проверить, прогуливаясь по его хозяевам.
Пройдите каждую цепочку один раз с ее вершины, чтобы мы были уверены, что вложенные копии остаются линейными. Проверяйте каждую ссылку один раз из каждой размонтированной копии.
Показать оригинальное описание (EN)
In the Linux kernel, the following vulnerability has been resolved: fs: don't silently unmount busy mounts The propagate_mount_busy() helper exists to decide whether a synchronous can suceed. It does that by looking at the copies of the victims in the mounts its parent propagates to. One of those functions from propagation hell. It skips a copy that has child mounts except for the case of a single child mount covering the copy's root. That algorithm used to be exact. It isn't anymore. Originally only childless copies were unmounted during propagation. And 1064f874abc0 ("mnt: Tuck mounts under others instead of creating shadow/side mounts.") ended up adding covered mounts to both sides in one go. Along came 99b19d16471e ("mnt: In propgate_umount handle visiting mounts in any order") and that started to unmount more than before: [1]: A copy of a mount is unmounted when each of its children is either its overmount or a copy of the victim itself. In the former case the overmount gets reparented. In the latter case the copy of the victim will end up being unmounted. So propagate_umount() ended up being rewritten without adjusting propagate_mount_busy(). And currently propagate_mount_busy() doesn't look at copies of the victim that have two or more children nor a single child that is not the overmount. So any such copy in [1] is not checked for references. The result is that a synchronous unmount succeeds, pulling out a mount that is still in use. A container can run into this with its own mounts. The host shares a tree with the container and the host has a mount in that tree: mount -t tmpfs none /mnt mount --make-shared /mnt mount -t tmpfs none /mnt/a The container's /mnt is a slave copy of the host mount. The container now takes a detached copy of the tree and mounts that copy beneath its propagated copy of /mnt/a and keeps the file descriptor to the tree open: unshare -m --propagation unchanged mount --make-rslave / fd = open_tree(AT_FDCWD, "/mnt", OPEN_TREE_CLONE | AT_RECURSIVE) move_mount(fd, "", AT_FDCWD, "/mnt/a", MOVE_MOUNT_BENEATH) grep /mnt /proc/self/mountinfo 775 355 ... /mnt ... master:646 777 775 ... /mnt/a ... master:646 776 777 ... /mnt/a ... master:647 778 777 ... /mnt/a/a ... master:647 The now attached tree (777) is now mounted beneath the container's copy of /mnt/a. That's also where the host mount sits (as seen from the host mount namespace). So the propagated copy (776) of the host's mount is on top of its root and the copy of that (778) is inside it. Now the host runs: umount /mnt/a and it succeeds. The moved tree tree and the copy inside of it are gone from the container. Now only the propagated copy is left and it got reparented to where it was before: grep /mnt /proc/self/mountinfo 775 355 ... /mnt ... master:646 776 775 ... /mnt/a ... But the file descriptor still refers to the moved tree. So a synchronous umount detached a mount that is still in use. Teach propagate_mount_busy() the same checks that propagate_umount() does. It now checks for a single victim mount without children for which it can assume that MNT_LOCKED is cleared on every copy like propagate_umount() does. The copies form chains. IOW, when a copy itself receives propagation from the victim's parent then the mount at the same mountpoint inside that copy is a copy as well. Whether a mount receives propagation from the victim's can simply be checked by walking its masters. Walk each chain once from its top so we are sure that nested copies stay linear. Check every reference once of every copy that gets unmounted.