Permission denied: как найти директорию без права поиска через namei
Практическая диагностика Permission denied в Linux: разложить путь через namei -l, найти промежуточную директорию без права поиска x и проверить точечное исправление без рекурсивного chmod.

В этой статье
Если Linux отвечает Permission denied для известного файла, сначала разложите путь командой namei -l. Она показывает режим, владельца и группу каждого компонента. Первый каталог без права поиска x для процесса — основная точка проверки; права конечного файла могут быть исправны.
Не начинайте с chmod -R и тем более с 777. Такая команда меняет больше объектов, чем требует диагностика, и может скрыть исходную причину.
Что показывает namei -l
namei проходит путь по компонентам, следует по символическим ссылкам и показывает, на каком участке разбор остановился. Ключ -l включает длинный формат: тип, биты режима, владельца и группу.
Для каждого промежуточного каталога процессу нужно право поиска. Если его нет, ядро возвращает EACCES — Permission denied. У каталога это право обозначается битом x; оно отличается от чтения списка имён по биту r. Это поведение описано в руководстве по разрешению путей Linux.
Фрагмент вывода | Что видно | Первая гипотеза |
|---|---|---|
d--------- locked | У каталога нет r, w и x | Путь остановится для процесса без обходных capability |
app - Permission denied | Следующий компонент не прочитан | Проверять права директории с именем locked |
-rw-r--r-- config.ini | Конечный файл виден | Промежуточные каталоги уже пройдены |
Входные условия и границы
Команды выполняются от имени того же пользователя или процесса, который получает ошибку.
Нужен полный абсолютный путь, а не только имя конечного файла.
Учебный тест выполнен в отдельном каталоге /tmp; рабочие файлы и службы не изменялись.
Проверка не заменяет отдельный разбор ACL, SELinux, AppArmor, NFS и контейнерных отображений.
Среда повторной проверки 13 октября 2026 года: Ubuntu 24.04.3 LTS, Linux 6.18.44, util-linux 2.39.3. Текущий процесс не имел capability для обхода обычных проверок DAC.
Минимальная диагностика
Подставьте фактический абсолютный путь проблемного файла:
namei -l /var/www/example/bitrix/.settings.php
Читайте результат сверху вниз. Если вывод остановился на каталоге, причина находится до конечного файла. Проверка только через ls -l конечного файла здесь не помогает: до него процесс ещё не дошёл.
Пример характерного фрагмента:
drwxr-xr-x root root mikhail-namei-lab-20261012
d--------- root root locked
app - Permission denied
Первый подозрительный компонент — locked. Строка app - Permission denied показывает место остановки, но менять права на app вслепую рано: директория app ещё не разрешена как компонент пути.

Воспроизводимый тест
В изолированной модели создаётся файл config.ini внутри каталога locked. Все родительские каталоги имеют обычные права, затем locked получает режим 0000.
lab_dir=/tmp/mikhail-namei-lab-20261012
locked_dir="$lab_dir/locked"
app_dir="$locked_dir/app"
config_file="$app_dir/config.ini"
install -d -m 0755 "$lab_dir" "$locked_dir" "$app_dir"
printf 'mode=training\n' >"$config_file"
chmod 0644 "$config_file"
chmod 0000 "$locked_dir"
После этого namei -l доходит до locked, но не может разрешить app. Проверка чтения возвращает код 1:
namei -l "$config_file"
test -r "$config_file"
printf 'read_check=%s\n' "$?"
d--------- root root locked
app - Permission denied
read_check=1
Для учебной директории владелец сохраняет rwx, а группе и остальным разрешаем только проход по x:
chmod 0711 "$locked_dir"
Повтор показывает полный путь, а проверка чтения возвращает 0:
drwx--x--x root root locked
drwxr-xr-x root root app
-rw-r--r-- root root config.ini
read_check=0
Режим locked | Наблюдение namei | Проверка чтения | Вывод |
|---|---|---|---|
0000 | Остановка перед app | 1 | Для директории отсутствует search-право (бит x) |
0711 | Путь показан полностью | 0 | Компонент можно пройти; файл читается |

Оба сценария выполнены дважды; итоговый скрипт завершился с кодом 0. Значение 0711 выбрано только для учебной модели и не является готовой рекомендацией для рабочего сервера.
Порядок на рабочем сервере
Зафиксируйте пользователя процесса, полный путь и точное сообщение ошибки.
Запустите namei -l от имени затронутого пользователя или в эквивалентном контексте.
Найдите первый компонент, после которого появляется Permission denied.
Сверьте ожидаемых владельца, группу и модель доступа именно для этого каталога.
Проверьте ACL и политики безопасности, если обычные биты режима выглядят корректно.
Меняйте только подтверждённый объект по согласованной политике доступа.
Повторите namei -l и исходную операцию; сохраните оба результата.
Остановитесь до изменения, если неизвестно, какой пользователь должен иметь доступ, эта директория используется несколькими сервисами или права управляются конфигурацией развёртывания. Ручная правка тогда может исчезнуть при следующем обновлении.
Почему проверка от root может ввести в заблуждение
Root или процесс с CAP_DAC_OVERRIDE либо CAP_DAC_READ_SEARCH способен обходить часть обычных проверок доступа. Поэтому успешный namei или cat от root не доказывает, что путь доступен пользователю PHP-FPM, резервного копирования или фонового задания.
Что namei не доказывает
namei не подтверждает доступ для другого пользователя или контейнера с иными UID, GID и mount namespace.
namei не подтверждает, что ACL разрешает доступ; ограничения ACL проверяют отдельно.
namei не показывает итоговое решение SELinux или AppArmor; контекст и профиль проверяют отдельно.
namei не подтверждает доступность сетевой файловой системы и правильность её правил сопоставления пользователей.
namei не подтверждает правильность содержимого и владельца конечного файла после успешного прохода пути.
Как подтвердить исправление
Результат принят, если namei -l показывает весь путь в нужном контексте, исходная операция завершается успешно, а изменение ограничено подтверждённым компонентом. По одному запуску от root выводить рано: повторите проверку тем же пользователем, который ранее получал Permission denied.
В учебном тесте критерий выполнен: при 0000 путь остановился и read_check был 1; при 0711 namei показал весь путь и read_check стал 0. Это подтверждает влияние права поиска x на промежуточную директорию, но не переносит выбранный режим на рабочий сервер.
If Linux returns Permission denied for a known file, first decompose the path using the namei -l command. It displays the mode, owner, and group for each component. The first directory lacking search permission x for the process is the primary check point; permissions on the final file may be correct.
Do not start with chmod -R, and certainly not with 777. Such a command modifies more objects than required for diagnosis and may obscure the root cause.
What namei -l shows
namei traverses the components of a path, follows symbolic links, and indicates where the resolution stopped. The -l flag enables long format: type, mode bits, owner, and group.
For each intermediate directory, the process requires search permission. If it is missing, the kernel returns EACCES — Permission denied. For a directory, this permission is denoted by the x bit; it differs from the read permission for listing names, which is the r bit. This behavior is described in the Linux path resolution guide.
Output snippet | What is visible | First hypothesis |
|---|---|---|
d--------- locked | The directory lacks r, w, and x | The path will stop for a process without bypass capabilities |
app - Permission denied | The next component was not read | Check permissions for a directory named locked |
-rw-r--r-- config.ini | The final file is visible | Intermediate directories have already been traversed |
Input conditions and boundaries
Commands are executed under the same user or process that receives the error.
A full absolute path is required, not just the final file name.
The test was run in a separate /tmp directory; working files and services were not modified.
This check does not replace a separate review of ACL, SELinux, AppArmor, NFS, and container mappings.
Re-test environment on October 13, 2026: Ubuntu 24.04.3 LTS, Linux 6.18.44, util-linux 2.39.3. The current process lacked the capability to bypass standard DAC checks.
Minimal diagnostics
Substitute the actual absolute path of the problematic file:
namei -l /var/www/example/bitrix/.settings.php
Read the output from top to bottom. If the output stops at a directory, the cause lies before the final file. Checking only the final file with ls -l here is unhelpful: the process has not yet reached it.
Example of a characteristic fragment:
drwxr-xr-x root root mikhail-namei-lab-20261012
d--------- root root locked
app - Permission denied
The first suspicious component is 'locked'. The line 'app - Permission denied' shows where the process stopped, but changing permissions on 'app' blindly is premature: the 'app' directory is not yet resolved as a path component.

Reproducible test
In the isolated model, a config.ini file is created inside the locked directory. All parent directories retain standard permissions, after which locked is set to mode 0000.
lab_dir=/tmp/mikhail-namei-lab-20261012
locked_dir="$lab_dir/locked"
app_dir="$locked_dir/app"
config_file="$app_dir/config.ini"
install -d -m 0755 "$lab_dir" "$locked_dir" "$app_dir"
printf 'mode=training\n' >"$config_file"
chmod 0644 "$config_file"
chmod 0000 "$locked_dir"
After this, namei -l reaches locked but cannot resolve app. The read check returns code 1:
namei -l "$config_file"
test -r "$config_file"
printf 'read_check=%s\n' "$?"
d--------- root root locked
app - Permission denied
read_check=1
For the test directory, the owner retains rwx permissions, while the group and others are allowed only traversal via x:
chmod 0711 "$locked_dir"
The repeat shows the full path, and the read check returns 0:
drwx--x--x root root locked
drwxr-xr-x root root app
-rw-r--r-- root root config.ini
read_check=0
Locked mode | namei observation | Read check | Output |
|---|---|---|---|
0000 | Stop before app | 1 | The directory lacks search permission (bit x is off) |
0711 | The path is displayed in full | 0 | The component is traversable; the file is readable |

Both scenarios were executed twice; the final script exited with code 0. The value 0711 was chosen only for the test model and is not a ready recommendation for a production server.
Order on a production server
Record the process user, the full path, and the exact error message.
Run namei -l as the affected user or in an equivalent context.
Find the first component after which "Permission denied" appears.
Verify the expected owner, group, and access mode specifically for that directory.
Check ACLs and security policies if standard mode bits appear correct.
Change only the confirmed object in accordance with an agreed access policy.
Repeat namei -l and the original operation; save both results.
Stop before making changes if it is unknown which user should have access, if this directory is used by multiple services, or if permissions are managed by deployment configuration. Manual edits may then be lost during the next update.
Why root checks can be misleading
Root or a process with CAP_DAC_OVERRIDE or CAP_DAC_READ_SEARCH can bypass some standard access checks. Therefore, a successful namei or cat command run as root does not prove that the path is accessible to PHP-FPM, backup processes, or background jobs.
What namei does not prove
namei does not confirm access for another user or a container with different UID, GID, and mount namespace.
namei does not confirm that ACLs allow access; ACL restrictions must be checked separately.
namei does not show the final SELinux or AppArmor decision; context and profile must be checked separately.
namei does not verify the availability of the network file system or the correctness of its user mapping rules.
namei does not verify the correctness of the final file's content and owner after a successful path traversal.
How to verify the fix
The result is accepted if namei -l shows the entire path in the correct context, the original operation completes successfully, and the change is limited to a confirmed component. It is premature to rely on a single run as root: repeat the check using the same user who previously received a Permission denied error.
In the training test, the criterion was met: with mode 0000 the path was blocked and read_check was 1; with mode 0711 namei showed the full path and read_check became 0. This confirms the impact of the search permission x on the intermediate directory, but does not apply the selected mode to the production server.





Обсуждение 0
Делись опытом и задавай вопросы. Комментарии без ссылок появляются после проверки редактором.
Пока никто не написал. Начни обсуждение.