Chcon не удалось применить частичный контекст к не помеченному файлу

Обновлено: 05.07.2024

Я получаю и ошибку, когда пытаюсь выполнить эту команду:

Ошибка, которую я получил:

Есть идеи, как ее решить?

2 ответа

У меня есть код VBS, который я использую для применения форматирования Excel к электронной таблице: Set xlObj = CreateObject(Excel.Application) Set xlFile = xlObj.WorkBooks.Open(C:\Documents and Settings\user\forms.xlsx) xlObj.Application.DisplayAlerts = False For Each Worksheet In.

При применении точек останова к файлу java в режиме отладки точки останова не останавливают поток управления этим файлом. Однако точки останова останавливают поток управления для другого файла в том же пакете. Когда я применяю точки останова к одному файлу, точка останова изменяется на круг с.

Попробуйте запустить это:

Там не совсем достаточно контекста того, что ваша цель состоит в том, чтобы ответить с большой точностью, но вот некоторые вещи, которые могут помочь.

Если вы хотите восстановить контекст в разделе дерева каталогов: restorecon -rnv / path/to/dir

флаги рекурсивные, без изменений и многословные

Вы также можете использовать use chcon --reference=file_with_good_perms your_file

ls-Z --> для просмотра контекстов selinux

Похожие вопросы:

У меня есть проект Prism с несколькими модулями. Сначала используйте код EF для создания базы данных. Я пытаюсь построить контекст с помощью частичного класса. Для каждого модуля будет свой.

Я понимаю, что, вероятно, буду сожалеть об этом всю свою жизнь, но. Есть ли какой-то способ применить XSLT к файлу XML без того, чтобы файл XML имел явную ссылку на файл XSLT? Лично я думал, что.

Я создаю пакет NuGet и сталкиваюсь с одной проблемой: как я могу применить преобразование к файлу, который не является web.config или app.config, я хотел бы сделать преобразование в файл.

У меня есть код VBS, который я использую для применения форматирования Excel к электронной таблице: Set xlObj = CreateObject(Excel.Application) Set xlFile = xlObj.WorkBooks.Open(C:\Documents and.

При применении точек останова к файлу java в режиме отладки точки останова не останавливают поток управления этим файлом. Однако точки останова останавливают поток управления для другого файла в том.

Мне нужна программа java, чтобы получить путь к определенному файлу.(в Linux г.) это должно выглядеть так FileInputStream svconfig = new FileInputStream( filepathinlinux);

Это частичный код, в котором я пытаюсь применить права доступа к файлу. fd=fopen(file_name,wb); fchmod(fd,(mode_t)perm); Где perm-целое число, например: 644 или 755 Я попробовал без кастинга с.

Как применить функцию elisp к определенному файлу, который не находится в открытом буфере? Например (my/apply delete-duplicate-lines

Я пишу регулярное выражение, которое будет использоваться, чтобы увидеть, содержит ли строка путь к файлу для системы linux как всю строку или путь к файлу для системы linux как только часть строки.

Я прочитал объяснение, данное в книге; но я не могу понять это ясно. Пожалуйста, используйте простую терминологию при объяснении команды.

Вы в этом случае:

chcon - изменить контекст безопасности файла; Вы можете проверить любой контекст безопасности файла с ls -Z .

-R - рекурсивно работать с файлами и каталогами.

--reference=RFILE - использовать контекст безопасности RFILE, а не указывать значение CONTEXT.

Таким образом, приведенная выше команда рекурсивно меняет контекст безопасности каждого файла с /var/www/html/install такового из /var/www/html .

Введите info coreutils 'chcon invocation' в терминал, и вы получите доступ к полному руководству.

Это руководство может помочь вам понять все о Security-Enhanced Linux (SELinux).

Спасибо за ваш ответ. Вы имели в виду, что контекст безопасности / var / www / html будет применяться ко всем файлам, которые находятся в каталоге / var / www / html / install. Не могли бы вы объяснить больше о "контексте безопасности". Спасибо. @Jai, вы можете проверить любой контекст безопасности файла с ls -Z

Если вы используете selinux , я предлагаю вам прочитать документацию Fedora.

Эта вторая ссылка предназначена для Fedora 13, но, IMO, остается самым последним документом о selinux.

Проблема, с которой вы столкнетесь, - это то, что chcon не переживет релабел и не восстановит.

5.7.1. Временные изменения: chcon команда chcon изменяет контекст SELinux для файлов. Тем не менее, изменения, внесенные с помощью команды chcon, не сохраняются после переименования файловой системы или выполнения команды / sbin / restorecon. Политика SELinux контролирует, могут ли пользователи изменять контекст SELinux для любого данного файла. При использовании chcon пользователи предоставляют весь или часть контекста SELinux для изменения. Неверный тип файла является частой причиной отказа SELinux в доступе.

chcon предназначен для временных изменений.

Вы почти наверняка захотите использовать restorecon

Если это не сработает, опубликуйте отказ AVC и предоставьте больше информации о том, что вы хотите сделать. Скорее всего, будет логическое значение, которое вам нужно будет настроить.

Whenever I'm trying to execute this line to configure SELinux to install xrdp from this tutorial:

I get these errors:

I'm on CentOS 7.2 64 bit.

51.8k 22 22 gold badges 131 131 silver badges 207 207 bronze badges 131 1 1 gold badge 1 1 silver badge 3 3 bronze badges

3 Answers 3

I'm also on CentOS 7, and this works for me:

While Thomas gave a pretty comprehensive answer, the solution is not that straightforward. I had to do a lot of try and error till I reached these two commands, which are actually working

Your command has to give more information. It has been discussed before (but I see no duplicates).

  • in chcon: can't apply partial context to unlabeled file while installing nagios with SELinux, Sergei Lomakov pointed out that it was first necessary to label the files using semanage .
  • in Linux chcon: can't apply partial context to unlabeled file, the suggested solution uses the complete type in the chcon command (but you would have to first determine the type using ls -Z ). The complete type would usually have a colon ( : ) in the name, because it represents a hierarchy.

For example, ls -lZ gives these tags for a sample listing:

and chcon is expecting something like unconfined_u:object_r:bin_t:s0 in its argument. A bin_t is only partial information.

The referenced procedure should have worked, and the use of chcon redundant. Checking my CentOS7, I happen to have xrdp installed, and a listing shows

The system_u field is the SELinux user, the object_r field is the role, bin_t is the type and s0 is the (default) level. The files in /usr/sbin get their context from a pattern shown by semanage fcontext -l (but there are a lot of matches). In following the guide, you may have removed the pattern for the xrdp — or even for /usr/sbin . However, you can be more explicit in the command, by specifying the user and role using chcon :

Alternatively, if the patterns are intact but (for instance) you had moved the files rather than installing them, you could repair things using

Product Site
Documentation Site

5.7. SELinux Contexts - Labeling Files

On systems running SELinux, all processes and files are labeled with a label that contains security-relevant information. This information is called the SELinux context. For files, this is viewed using the ls -Z command:

In this example, SELinux provides a user ( unconfined_u ), a role ( object_r ), a type ( user_home_t ), and a level ( s0 ). This information is used to make access control decisions. On DAC systems, access is controlled based on Linux user and group IDs. SELinux policy rules are checked after DAC rules. SELinux policy rules are not used if DAC rules deny access first.

There are multiple commands for managing the SELinux context for files, such as chcon , semanage fcontext , and restorecon .

5.7.1. Temporary Changes: chcon

The chcon command changes the SELinux context for files. These changes do not survive a file system relabel, or the /sbin/restorecon command. SELinux policy controls whether users are able to modify the SELinux context for any given file. When using chcon , users provide all or part of the SELinux context to change. An incorrect file type is a common cause of SELinux denying access.

Quick Reference
Changing a File's or Directory's Type

The following example demonstrates changing the type, and no other attributes of the SELinux context:

Run the cd command without arguments to change into your home directory.

Run the touch file1 command to create a new file. Use the ls -Z file1 command to view the SELinux context for file1 :

In this example, the SELinux context for file1 includes the SELinux unconfined_u user, object_r role, user_home_t type, and the s0 level. For a description of each part of the SELinux context, refer to Chapter 3, SELinux Contexts.

Run the chcon -t samba_share_t file1 command to change the type to samba_share_t . The -t option only changes the type. View the change with ls -Z file1 :

Use the /sbin/restorecon -v file1 command to restore the SELinux context for the file1 file. Use the -v option to view what changes:

In this example, the previous type, samba_share_t , is restored to the correct, user_home_t type. When using targeted policy (the default SELinux policy in Fedora 11), the /sbin/restorecon command reads the files in the /etc/selinux/targeted/contexts/files/ directory, to see which SELinux context files should have.

The example in this section works the same for directories, for example, if file1 was a directory.

Changing a Directory and its Contents Types

As the Linux root user, run the mkdir /web command to create a new directory, and then the touch /web/file <1,2,3>command to create 3 empty files ( file1 , file2 , and file3 ). The /web/ directory and files in it are labeled with the default_t type:

As the Linux root user, run the /sbin/restorecon -R -v /web/ command to restore the default SELinux contexts:

Refer to the chcon (1) manual page for further information about chcon .

Type Enforcement is the main permission control used in SELinux targeted policy. For the most part, SELinux users and roles can be ignored.

Читайте также: