В ядре Linux была устранена следующая уязвимость: tun: Require CAP_NET_ADMIN для подключения к бесхозному устройству Twenty лет назад я сделал создание устройства tuntap, требующее CAP_NET_ADMIN in commit ca6bb5d7ab22 ("[NET]: Require CAP_NET_ADMIN для создания устройств tuntap.") Идея состояла в том, чтобы разрешить разрешения на /dev/net/tun быть смягченным до 0666 и, таким образом, позволить владельцам устройств tun, назначенных с TUNSETOWNER, фактически открыть его и получить их устройства. То, что мы упустили в то время, было то, что постоянные устройства с владельцем * no * уже были по существу потребляемыми в мире, и любой, кто мог открыть узел устройства, также мог прикрепиться к ним. Даже тогда использование постоянных устройств без явно установленного владельца — на (ложном) предположении, что CAP_NET_ADMIN потребуется их открыть — не было вопиющей ошибкой пользовательского пространства.
Бывают случаи, когда имеет смысл отделить создание / конфигурацию сетевого устройства от процесса, который в него упаковывает пакеты. Since then, TUNSETGROUP was added a year later in commit 8c644623fe7e ("[NET]: Allow group ownership of TUN/TAP devices."). Его сообщение о фиксации отметило, что если и uid, и gid установлены, оба должны соответствовать (сам по себе странный выбор), но все же не то, что с *ни один из * набор, разрешение вообще не требовалось.
Затем в 2012 году commit c8d68e6be1c3 («tuntap: multiqueue support») позволил подключать новые очереди к устройству с момента его создания, не имея возможности для пользовательского пространства закрыть гонку между созданием и последующим TUNSETOWNER,GROUP. В 2024 году commit 3ca459eaba1bf («tun: fix group permission check») попытался исправить ситуацию, чтобы быть разумнее: только требовать, чтобы пользователь * или * группа соответствовала стандартным разрешениям POSIX, и требовать CAP_NET_ADMIN, если ни пользователь, ни группа не разрешили доступ (хотя он поставил проверку CAP_NET_ADMIN на первое место и ошибочно сообщил бы о возможности, даже когда она не использовалась). Это исправление было отменено в commit a70c7b3cbc06 («tun: return fix group permission check») из-за того, что оно якобы вызвало регрессию в наборе тестов selinux, который * ожидал *, что вложение будет успешным, когда оно не авторизовано ни пользователем, ни группой, ни CAP_NET_ADMIN: https://lore.kernel.org/netdev/CAFqZXNtkCBT4f+PwyVRmQGoT3p1eVa01fCG_aNtpt6dakXncUg@mail.gmail.com/ We не должен нарушать UAPI.
Но мы не должны рассматривать тестовый случай с селинуксом, который намеренно использует недостаток безопасности, чтобы быть UAPI, который стоит сохранить. С этой целью я закрепил его в selinux-testuite commit b2f894f0016b ("tests/tun_tap: установить владельца на устройство для перемаркировки тестов»). Итак: исправьте отсутствие проверки CAP_NET_ADMIN на устройствах, которые * не были назначены владельцем или группой, оставляя странную модель владения Tun, как это было (пользователь * и * группа должны соответствовать, если оба установлены).
Если кто-то все еще хочет исправить последнее (что на самом деле не было причиной предыдущей попытки было отменено), они могут сделать это под отдельным прикрытием. Разрешить подключение к существующему устройству только в том случае, если установлен владелец и/или группа, а абонент соответствует всем установленным параметрам, или если абонент имеет CAP_NET_ADMIN. Единственное изменение в поведении заключается в том, что устройство без владельца или группы теперь требует подключения CAP_NET_ADMIN — именно ту лазейку, которую мы хотим закрыть.
И поставить чек CAP_NET_ADMIN в нужное место на этот раз.
Показать оригинальное описание (EN)
In the Linux kernel, the following vulnerability has been resolved: tun: Require CAP_NET_ADMIN to attach to an ownerless device Twenty years ago I made creating a tuntap device require CAP_NET_ADMIN in commit ca6bb5d7ab22 ("[NET]: Require CAP_NET_ADMIN to create tuntap devices.") The idea was to allow the permissions on /dev/net/tun to be relaxed to 0666 and thus allow owners of tun devices assigned with TUNSETOWNER to actually open it and get at their devices. What we missed at the time was that persistent devices with *no* owner were already essentially world-consumable, and anyone who could open the device node could also attach to those. Even then, using persistent devices with no explicitly set owner — on the (false) presumption that CAP_NET_ADMIN would be required to open them — wasn't an egregious userspace bug. There are cases where it does make sense to separate the creation/configuration of the netdevice, from the process which shovels packets into it. Since then, TUNSETGROUP was added a year later in commit 8c644623fe7e ("[NET]: Allow group ownership of TUN/TAP devices."). Its commit message noted that if both uid and gid are set, both have to match (in itself a bizarre choice) — but still not that with *neither* set, no permission at all was required. Then in 2012 commit c8d68e6be1c3 ("tuntap: multiqueue support") allowed new queues to be attached to a device from the moment of its creation, with no way for userspace to close the race between creation and a subsequent TUNSET{OWNER,GROUP}. In 2024, commit 3ca459eaba1bf ("tun: fix group permission check") tried to fix things to be saner: only require the user *or* the group to match, in line with standard POSIX permissions, and require CAP_NET_ADMIN if neither the user nor group authorised the access (although it put the CAP_NET_ADMIN check first, and would wrongly have reported the capability as having been used even when it was not). That fix was reverted in commit a70c7b3cbc06 ("tun: revert fix group permission check") due to allegedly causing a regression in an selinux test suite which *expected* the attachment to succeed when authorised by none of user, group, nor CAP_NET_ADMIN: https://lore.kernel.org/netdev/CAFqZXNtkCBT4f+PwyVRmQGoT3p1eVa01fCG_aNtpt6dakXncUg@mail.gmail.com/ We should not break UAPI. But we don't have to consider an selinux test case which deliberately exercises a security flaw to be UAPI worth preserving either. To which end, I have fixed it in selinux-testsuite commit b2f894f0016b ("tests/tun_tap: set an owner on the device for the relabel tests"). So: fix the lack of CAP_NET_ADMIN check on devices which *haven't* been assigned an owner or group, while leaving the weird tun ownership model as it was (user *and* group have to match, if both are set). If someone still wants to fix the latter (which wasn't actually the reason the previous attempt was reverted), they can do it under separate cover. Permit attaching to an existing device only if an owner and/or group was set and the caller matches all that were set, or if the caller has CAP_NET_ADMIN. The only behavioural change is that a device with no owner or group now requires CAP_NET_ADMIN to attach — precisely the loophole we want to close. And put the CAP_NET_ADMIN check in the right place this time.
Характеристики атаки
Последствия
Строка CVSS v3.1