Смена прав доступа пользователю в Linux
Режим доступа к файлу можно изменить с помощью команды chmod. Изменять права доступа к файлу позволено только его владельцу либо пользователю root. В UNIX-системах код задается в виде восьмеричного числа. Также поддерживается система мнемонических (буквенных) обозначений. Первый способ удобнее для системного администратора, но при этом можно задать только абсолютное значение режима доступа. А используя мнемонический синтаксис, вы можете сбрасывать и устанавливать отдельные параметры, к примеру, добавить право на чтение либо убрать право на запись.
Первым аргументом команды chmod является спецификация прав доступа, то есть восьмеричное число (774, 777 и т.д.) либо мнемоническое обозначение (r+o, w-u и т.д.). Второй и последующий аргументы — имена файлов, права доступа к которым подлежат изменению. При использовании восьмеричной нотации первая цифра относится к владельцу, вторая — к группе, а третья — к остальным пользователям.
Права доступа к файлам подразделяются на следующие:
r — право на чтение данных.
w — право на изменение содержимого (запись – только изменение содержимого, но не удаление).
x — право на исполнение файла.
Теперь о правах доступа к папке (директории):
r — право на чтение директории (можно прочитать содержимое директории, т.е. получить список объектов, находящихся в ней)
w — право на изменение содержимого директории (можно создавать и удалять объекты в этой директории, причем если вы имеете право на запись, то удалять вы сможете даже те файлы, которые вам не принадлежат)
x — право, которое позволяет вам войти в директорию (это право всегда проверяется в первую очередь, и даже если вы имеете все нужные права на объект, который закопан глубоко в цепочке директорий, но не имеете права “X” для доступа хотя бы к одной директории на пути к этому файлу, то к нему вы так и не пробьетесь)
В таблице указано восемь возможных комбинаций:
Восьмеричное число | Двоичное число | Режим доступа |
---|---|---|
0 | 000 | — |
1 | 001 | —x |
2 | 010 | -w- |
3 | 011 | -wx |
4 | 100 | r— |
5 | 101 | r-x |
6 | 110 | rw- |
7 | 111 | rwx |
chmod 711 myfile
предоставляет владельцу все права, а всем остальным пользователям — только право выполнения, а команда:
chmod 775 myfile
предоставляет владельцу и группе все права, а остальным пользователям запрещает изменение файла. Для смены прав доступа необходимо находиться в директории, где расположен файл, либо указывать полный путь:
chmod 775 /var/www/myfile
Для применения прав доступа ко всем вложенным в директорию файлам и папкам (рекурсивно) необходимо в команду добавить ключ -R. То есть команда будет выглядеть как:
chmod -R 711 myfile
Примеры мнемонических спецификаций команды chmod:
Спецификация | Значение |
---|---|
u+w | Владельцу файла дополнительно дается право выполнения. |
ug=rw,o=r | Владельцу и группе предоставляется право чтения/записи, остальным пользователям — право чтения. |
a-x | Все пользователи лишаются права выполнения. |
ug=srx,o= | Владельцу и группе дается право чтения/выполнения, устанавливается также бит SUID; остальным пользователям запрещен доступ к файлу. |
g=u | Группе назначаются такие же права, что и владельцу |
Символ u (“user”) обозначает владельца файла, символ g (“group”) — группу, символ о (“others”) — других пользователей, символ a (“all”) — всех пользователей сразу.
То есть, если необходимо убрать право на редактирование всех вложенных файлов и папок у других пользователей, то с помощью мнемонических обозначений команда будет выглядеть следующим образом:
chmod o-w -R myfile
В качестве примера мы будем устанавливать права доступа 777 для папки /var/www/mysite и всех вложенных в нее файлов и каталогов.
ВНИМАНИЕ! Установка прав доступа 777 используется исключительно в качестве примера, их использование может привести к уязвимости сервера!
Смена прав доступа
SSH
- Входим по протоколу SSH на ВПС с root привилегиями.
- Переходим с помощью команды cd в директорию, где расположена необходимая нам папка. В данном случае это /var/www:
cd /var/www
chmod -R 777 mysite
SFTP
Для подключения к серверу по протоколу SFTP мы будем использовать программу FileZilla. Данная программа бесплатна, поддерживает русский язык и кросплатформенна. Вы можете скачать ее с официального сайта: https://filezilla-project.org/. Обратите внимание, что в левой колонке отображает дерево каталогов Вашего компьютера, а в правой удаленной машины, в данном случае ВПС.
- Подключаемся к ВПС с root привилегиями по SFTP.
- Переходим в каталог /var/www
- Нажимаем правой кнопкой мышки на папке mysite и выбираем «Права доступа к файлу»
- Во всплывающем окне устанавливаем необходимые права 777 и нажимаем «Перенаправить во вложенные каталоги» и выбираем «Применить ко всем каталогам и файлам» и нажимаем ОК.
DirectAdmin
К сожалению, в КП DirectAdmin не предоставляется доступ к корневой файловой системе с помощью встроенного менеджера файлов. В связи с этим, в качестве примера, мы изменим права доступа для директории /domains/domain.com/public_html/mysite
- Входим в КП DirectAdmin
- Нажимаем кнопку Files в панели сверху
- Перейти в папку /domains/domain.com/public_html
- Поставить галочку напротив каталога mysite, после чего установить права доступа к папке 777 и поставить галочку напротив Recursive, для применения данных прав доступа ко всем вложенным файлам и папкам.
- Нажать set Permission
cPanel
В cPanel также не предоставляется доступ к корневой директории, в связи с чем мы сменим, в качестве примера, права доступа для папки /public_html/mysite. Обратите внимание, что менеджер файлов доступен только на уровне пользователя.
- Войти в cPanel на уровне пользователя.
- Перейти в Файлы → Диспетчер файлов.
- Перейти в директорию /public_html
- Выделить папку mysite и нажать «Разрешения»
- В всплывающем окне установить необходимые права доступа и нажать «Change Permissions». Обратите внимание, что файловый менеджер cPanel не умеет изменять права для всех вложенных файлов и папок. Рекурсивно сменить права доступа Вы всегда сможете с помощью SSH либо SFTP протоколов.
Что такое set perm recursive в программирование
По отношению к файлу, такие права хорошо понятны: доступ для чтения позволяет читать содержимое (включая копирование), доступ для записи позволяет менять содержимое, доступ для исполнения позволяет запускать (работает для программ).
БЕЗОПАСНОСТЬ исполняемые файлы с setuid и setgid
Two particular rights are relevant to executable files: setuid and setgid (symbolized with the letter “s”). Note that we frequently speak of “bit”, since each of these Boolean values can be represented by a 0 or a 1. These two rights allow any user to execute the program with the rights of its owner or its group, respectively. This mechanism grants access to features requiring higher level permissions than those you would usually have.
Поскольку setuid -программа, принадлежащая root, систематически запускается с правами суперпользователя, крайне важно убедиться в её безопасности и надёжности. Действительно, пользователь, которому удастся заставить её вызвать другую произвольную программу, сможет представиться как root и получить все права в системе.
If you require running a program under a different user or if a program requires higher permissions, the sudo , su , or runuser commands are usually better choices than using these bits (see Раздел 8.9.4, «Разделение Прав Администратора (делегирование части полномочий другому пользователю или старшему администратору)»).
Каталоги обрабатываются иначе. Доступ на чтение даёт право получить список его содержимого (файлов и каталогов), доступ на запись позволяет создавать и удалять файлы, а доступ на исполнение позволяет проходить через него (в частности переходить в него с помощью команды cd ). Возможность проходить через каталог, не имея возможности прочесть его, позволяет получить доступ к файлам внутри него, если они известны по имени, но не находить их, если о их существовании или их точных именах не известно.
БЕЗОПАСНОСТЬ Каталог с setgid и sticky bit
Бит setgid применим и к каталогам. Любой вновь созданный файл внутри таких каталогов автоматически присваивается группе-владельцу родительского каталога вместо того, чтобы унаследовать основную группу создателя, как происходит обычно. Эта настройка позволяет пользователю не изменять свою основную группу (с помощью команды newgrp ) при работе в дереве файлов, общих для нескольких пользователей из одной конкретной группы.
Так называемый «sticky bit» (обозначаемый буквой «t») является разрешением, имеющим смысл только для каталогов. Он, в частности, используется для временных каталогов, куда у всех есть доступ на запись (например /tmp/ ): он ограничивает возможность удаления файлов, так что только их владелец (или владелец родительского каталога) может это сделать. Если бы данной функции не было, любой мог бы удалить файлы других пользователей в /tmp/ .
Три команды для управления разрешениями, связанными с файлом:
chown пользователь файл изменяет владельца файла;
chgrp группа файл меняет группу-владельца;
chmod права файл изменяет разрешения на файл.
Есть два способа представления прав. Из них символьное, пожалуй, более легко для понимания и запоминания. В нём используются указанные выше символы. Можно определить права для каждой категории пользователей ( u / g / o ), присвоив их явно (с помощью = ), добавив ( + ) или отняв ( — ). Так, выражение u=rwx,g+rw,o-r даёт владельцу права на чтение, запись и исполнение, добавляет права на чтение и запись для группы-владельца и отнимает право на чтение у остальных пользователей. Права, не затрагиваемые добавлением или отъёмом, остаются без изменений. Буква a (от «all») обозначает все три категории пользователей, так что a=rx даёт всем трём категориям одинаковые права (читать и исполнять, но не записывать).
В цифровом (восьмеричном) представлении каждому праву соответствует конкретное значение: 4 — чтению, 2 — записи, 1 — исполнению. Каждая комбинация прав соответствует сумме этих чисел. Каждое значение затем присваивается своей категории пользователей, будучи записанным подряд с остальными в обычном порядке (владелец, группа, остальные).
For instance, the chmod 754 file command will set the following rights: read, write and execute for the owner (since 7 = 4 + 2 + 1); read and execute for the group (since 5 = 4 + 1); read-only for others. The 0 (zero) means no rights; thus chmod 600 file allows for read/write rights for the owner, and no rights for anyone else. The most frequent right combinations are 755 for executable files and directories, and 644 for data files.
Для представления в таком виде специальных прав можно указать в начале четвёртую цифру в соответствии с тем же принципом, где битам setuid , setgid sticky соответствуют 4, 2 и 1. chmod 4754 установит бит setuid наравне с вышеописанными правами.
Заметьте, что для восьмеричного представления возможна только установка всех прав сразу, нельзя добавить новое правило, как например, доступ для чтения для владельца группы — пользователь должен, учитывая существующие права, вычислить новое соответствующее значение.
СОВЕТ Рекурсивная работа
Иногда требуется изменить права для целого дерева файлов. У всех вышеуказанных команд есть опция -R , при использовании которой программа рекурсивно обходит подкаталоги.
The distinction between directories and files sometimes causes problems with recursive operations. That is why the “ X ” letter has been introduced in the symbolic representation of rights. It also represents the right to execute, but it applies differently to directories and files.
For directories it adds executable permissions to the chosen user(s). For files, it adds the executable bit only if at least one of the users (owner, group, or others) already has executable permissions. Let’s demonstrate it, because this bit can be confusing:
$
ls test.txt
-rw-r--r-- 1 daniel daniel 0 18. Nov 01:07 test.txt
$
chmod u+X test.txt
$
ls test.txt
-rw-r--r-- 1 daniel daniel 0 18. Nov 01:07 test.txt
$
chmod o+x test.txt
$
ls test.txt
-rw-r--r-x 1 daniel daniel 0 18. Nov 01:07 test.txt
$
chmod u+X test.txt
$
ls test.txt
-rwxr--r-x 1 daniel daniel 0 18. Nov 01:07 test.txt
The example shows a typical file with its default permissions: its owner can read and write it, the owner’s group and all other users can read it. The next operation ( u+X ) won’t add executable permissions for the owner of the file, because permissions to execute have not been assigned. The operation has no effect on the file. Next we assign execute rights for «other» users and repeat the operation. This time it is successful, because at least one user group already had executable permissions.
It is a misconception that this bit will only affect directories. If files and directories have mixed permissions, it is often a good idea to use the find command to locate the targets you want to operate on.
TIP Changing the user and group together
Frequently you want to change the group of a file at the same time that you change the owner. The chown command has a special syntax for that: chown user:group file . This syntax can also be used to recursively ( -R ) change the ownership of a whole directory.
УГЛУБЛЯЕМСЯ umask
When an application creates a file, it assigns indicative permissions, knowing that the system automatically removes certain rights, given by the command umask . Enter umask in a shell; you will see a mask such as 0022 . This is simply an octal representation of the rights to be systematically removed. In this case, the write right for the group and other users: With the above umask value, the default for directories 777 becomes 755 and the default permissions for files 666 become 644 .
The system’s default value is handled by pam_umask (8) and /etc/login.defs .
If you give it a new octal value, the umask command modifies the mask. Used in a shell initialization file (for example, ~/.bashrc or ~/.profile ), it will effectively change the default mask for your work sessions.
9.3.2. ACLs — Access Control Lists
Many filesystems, e.g. Btrfs, Ext3, Ext4, JFS, XFS, etc., support the use of Access Control Lists (ACLs). These extend the basic features of file ownership and permission, described in the previous section, and allow for a more fine-grained control of each (file) object. For example: A user wants to share a file with another user and that user should only be able to read the file, but not write or change it.
For some of the filesystems, the usage of ACLs is enabled by default (e.g. Btrfs, Ext3, Ext4). For other filesystems or older systems it must be enabled using the acl mount option — either in the mount command directly or in /etc/fstab . In the same way the usage of ACLs can be disabled by using the noacl mount option. For Ext* filesystems one can also use the tune2fs -o [no]acl /dev/device command to enable/disable the usage of ACLs by default. The default values for each filesystem can usually be found in their homonym manual pages in section 5 ( filesystem (5) ) or in mount (8) .
After enabling ACLs, permissions can be set using the setfacl (1) command, while getfacl (1) allows one to retrieve the ACLs for a given object or path. These commands are part of the acl package. With setfacl one can also configure newly created files or directories to inherit permissions from the parent directory. It is important to note that ACLs are processed in their order and that an earlier entry that fits the situation has precedence over later entries.
If a file has ACLs set, the output of the ls -l command will show a plus-sign after the traditional permissions. When using ACLs, the chmod command behaves slightly different, and umask might be ignored. The extensive documentation, e.g. acl (5) contains more information.
Что такое set perm recursive в программирование
chmod [ -R ] mode file .
DESCRIPTION
The chmod utility shall change any or all of the file mode bits of the file named by each file operand in the way specified by the mode operand.
It is implementation-defined whether and how the chmod utility affects any alternate or additional file access control mechanism (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.4, File Access Permissions) being used for the specified file.
Only a process whose effective user ID matches the user ID of the file, or a process with the appropriate privileges, shall be permitted to change the file mode bits of a file.
OPTIONS
The chmod utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.
The following option shall be supported: -R Recursively change file mode bits. For each file operand that names a directory, chmod shall change the file mode bits of the directory and all files in the file hierarchy below it.
OPERANDS
The following operands shall be supported: mode Represents the change to be made to the file mode bits of each file named by one of the file operands; see the EXTENDED DESCRIPTION section. file A pathname of a file whose file mode bits shall be modified.
STDIN
INPUT FILES
ENVIRONMENT VARIABLES
The following environment variables shall affect the execution of chmod : LANG Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.) LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_CTYPE Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments). LC_MESSAGES Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error. NLSPATH Determine the location of message catalogs for the processing of LC_MESSAGES .
ASYNCHRONOUS EVENTS
STDOUT
STDERR
The standard error shall be used only for diagnostic messages.
OUTPUT FILES
EXTENDED DESCRIPTION
The mode operand shall be either a symbolic_mode expression or a non-negative octal integer. The symbolic_mode form is described by the grammar later in this section.
Each clause shall specify an operation to be performed on the current file mode bits of each file . The operations shall be performed on each file in the order in which the clause s are specified.
The who symbols u , g , and o shall specify the user , group , and other parts of the file mode bits, respectively. A who consisting of the symbol a shall be equivalent to ugo .
The perm symbols r , w , and x represent the read , write , and execute / search portions of file mode bits, respectively. The perm symbol s shall represent the set-user-ID-on-execution (when who contains or implies u ) and set-group-ID-on-execution (when who contains or implies g ) bits.
The perm symbol X shall represent the execute/search portion of the file mode bits if the file is a directory or if the current (unmodified) file mode bits have at least one of the execute bits (S_IXUSR, S_IXGRP, or S_IXOTH) set. It shall be ignored if the file is not a directory and none of the execute bits are set in the current file mode bits.
The permcopy symbols u , g , and o shall represent the current permissions associated with the user, group, and other parts of the file mode bits, respectively. For the remainder of this section, perm refers to the non-terminals perm and permcopy in the grammar.
If multiple actionlist s are grouped with a single wholist in the grammar, each actionlist shall be applied in the order specified with that wholist . The op symbols shall represent the operation performed, as follows: + If perm is not specified, the ‘+’ operation shall not change the file mode bits.
If who is not specified, the file mode bits represented by perm for the owner, group, and other permissions, except for those with corresponding bits in the file mode creation mask of the invoking process, shall be set.
Otherwise, the file mode bits represented by the specified who and perm values shall be set. — If perm is not specified, the ‘-‘ operation shall not change the file mode bits.
If who is not specified, the file mode bits represented by perm for the owner, group, and other permissions, except for those with corresponding bits in the file mode creation mask of the invoking process, shall be cleared.
Otherwise, the file mode bits represented by the specified who and perm values shall be cleared. = Clear the file mode bits specified by the who value, or, if no who value is specified, all of the file mode bits specified in this volume of IEEE Std 1003.1-2001.
If perm is not specified, the ‘=’ operation shall make no further modifications to the file mode bits.
If who is not specified, the file mode bits represented by perm for the owner, group, and other permissions, except for those with corresponding bits in the file mode creation mask of the invoking process, shall be set.
Otherwise, the file mode bits represented by the specified who and perm values shall be set.
When using the symbolic mode form on a regular file, it is implementation-defined whether or not:
Requests to set the set-user-ID-on-execution or set-group-ID-on-execution bit when all execute bits are currently clear and none are being set are ignored.
Requests to clear all execute bits also clear the set-user-ID-on-execution and set-group-ID-on-execution bits.
Requests to clear the set-user-ID-on-execution or set-group-ID-on-execution bits when all execute bits are currently clear are ignored. However, if the command ls -l file writes an s in the position indicating that the set-user-ID-on-execution or set-group-ID-on-execution is set, the commands chmod u-s file or chmod g-s file , respectively, shall not be ignored.
When using the symbolic mode form on other file types, it is implementation-defined whether or not requests to set or clear the set-user-ID-on-execution or set-group-ID-on-execution bits are honored.
If the who symbol o is used in conjunction with the perm symbol s with no other who symbols being specified, the set-user-ID-on-execution and set-group-ID-on-execution bits shall not be modified. It shall not be an error to specify the who symbol o in conjunction with the perm symbol s .
The perm symbol t shall specify the S_ISVTX bit. When used with a file of type directory, it can be used with the who symbol a , or with no who symbol. It shall not be an error to specify a who symbol of u , g , or o in conjunction with the perm symbol t , but the meaning of these combinations is unspecified. The effect when using the perm symbol t with any file type other than directory is unspecified.
For an octal integer mode operand, the file mode bits shall be set absolutely.
For each bit set in the octal number, the corresponding file permission bit shown in the following table shall be set; all other file permission bits shall be cleared. For regular files, for each bit set in the octal number corresponding to the set-user-ID-on-execution or the set-group-ID-on-execution, bits shown in the following table shall be set; if these bits are not set in the octal number, they are cleared. For other file types, it is implementation-defined whether or not requests to set or clear the set-user-ID-on-execution or set-group-ID-on-execution bits are honored.
Octal | Mode Bit | Octal | Mode Bit | Octal | Mode Bit | Octal | Mode Bit | |
4000 | S_ISUID | 0400 | S_IRUSR | 0040 | S_IRGRP | 0004 | S_IROTH | |
2000 | S_ISGID | 0200 | S_IWUSR | 0020 | S_IWGRP | 0002 | S_IWOTH | |
1000 | S_ISVTX | 0100 | S_IXUSR | 0010 | S_IXGRP | 0001 | S_IXOTH |
When bits are set in the octal number other than those listed in the table above, the behavior is unspecified.
Grammar for chmod
The grammar and lexical conventions in this section describe the syntax for the symbolic_mode operand. The general conventions for this style of grammar are described in Grammar Conventions . A valid symbolic_mode can be represented as the non-terminal symbol symbolic_mode in the grammar. This formal syntax shall take precedence over the preceding text syntax description.
The lexical processing is based entirely on single characters. Implementations need not allow s within the single argument being processed.
%start symbolic_mode %% symbolic_mode : clause | symbolic_mode ',' clause ; clause : actionlist | wholist actionlist ; wholist : who | wholist who ; who : 'u' | 'g' | 'o' | 'a' ; actionlist : action | actionlist action ; action : op | op permlist | op permcopy ; permcopy : 'u' | 'g' | 'o' ; op : '+' | '-' | '=' ; permlist : perm | perm permlist ; perm : 'r' | 'w' | 'x' | 'X' | 's' | 't' ;
EXIT STATUS
The following exit values shall be returned: 0 The utility executed successfully and all requested changes were made. >0 An error occurred.
CONSEQUENCES OF ERRORS
The following sections are informative.
APPLICATION USAGE
Some implementations of the chmod utility change the mode of a directory before the files in the directory when performing a recursive ( -R option) change; others change the directory mode after the files in the directory. If an application tries to remove read or search permission for a file hierarchy, the removal attempt fails if the directory is changed first; on the other hand, trying to re-enable permissions to a restricted hierarchy fails if directories are changed last. Users should not try to make a hierarchy inaccessible to themselves.
Some implementations of chmod never used the process’ umask when changing modes; systems conformant with this volume of IEEE Std 1003.1-2001 do so when who is not specified. Note the difference between:
chmod a-w file
which removes all write permissions, and:
chmod -- -w file
which removes write permissions that would be allowed if file was created with the same umask .
Conforming applications should never assume that they know how the set-user-ID and set-group-ID bits on directories are interpreted.
EXAMPLES
Mode | Results | |
a += | Equivalent to a +, a =; clears all file mode bits. | |
go +-w | Equivalent to go +, go — w ; clears group and other write bits. | |
g = o — w | Equivalent to g = o , g — w ; sets group bit to match other bits and then clears group write bit. | |
g — r + w | Equivalent to g — r , g + w ; clears group read bit and sets group write bit. | |
uo = g | Sets owner bits to match group bits and sets other bits to match group bits. |
RATIONALE
The functionality of chmod is described substantially through references to concepts defined in the System Interfaces volume of IEEE Std 1003.1-2001. In this way, there is less duplication of effort required for describing the interactions of permissions. However, the behavior of this utility is not described in terms of the chmod () function from the System Interfaces volume of IEEE Std 1003.1-2001 because that specification requires certain side effects upon alternate file access control mechanisms that might not be appropriate, depending on the implementation.
Implementations that support mandatory file and record locking as specified by the 1984 /usr/group standard historically used the combination of set-group-ID bit set and group execute bit clear to indicate mandatory locking. This condition is usually set or cleared with the symbolic mode perm symbol l instead of the perm symbols s and x so that the mandatory locking mode is not changed without explicit indication that that was what the user intended. Therefore, the details on how the implementation treats these conditions must be defined in the documentation. This volume of IEEE Std 1003.1-2001 does not require mandatory locking (nor does the System Interfaces volume of IEEE Std 1003.1-2001), but does allow it as an extension. However, this volume of IEEE Std 1003.1-2001 does require that the ls and chmod utilities work consistently in this area. If ls -l file indicates that the set-group-ID bit is set, chmod g-s file must clear it (assuming appropriate privileges exist to change modes).
The System V and BSD versions use different exit status codes. Some implementations used the exit status as a count of the number of errors that occurred; this practice is unworkable since it can overflow the range of valid exit status values. This problem is avoided here by specifying only 0 and >0 as exit values.
The System Interfaces volume of IEEE Std 1003.1-2001 indicates that implementation-defined restrictions may cause the S_ISUID and S_ISGID bits to be ignored. This volume of IEEE Std 1003.1-2001 allows the chmod utility to choose to modify these bits before calling chmod () (or some function providing equivalent capabilities) for non-regular files. Among other things, this allows implementations that use the set-user-ID and set-group-ID bits on directories to enable extended features to handle these extensions in an intelligent manner.
The X perm symbol was adopted from BSD-based systems because it provides commonly desired functionality when doing recursive ( -R option) modifications. Similar functionality is not provided by the find utility. Historical BSD versions of chmod , however, only supported X with op +; it has been extended in this volume of IEEE Std 1003.1-2001 because it is also useful with op =. (It has also been added for op — even though it duplicates x , in this case, because it is intuitive and easier to explain.)
The grammar was extended with the permcopy non-terminal to allow historical-practice forms of symbolic modes like o = u -g (that is, set the «other» permissions to the permissions of «owner» minus the permissions of «group»).
FUTURE DIRECTIONS
SEE ALSO
ls , umask , the System Interfaces volume of IEEE Std 1003.1-2001, chmod ()
Что такое set perm recursive в программирование
FAQ по созданию патча update.zip для прошивки через рекавери
Редактирование Updater-script. Информация, решения, команды, подпись патчей.
Инструкция по установке системных и пользовательских приложений с помощью recovery
Редактирование установленной прошивки и удаление системных приложений
(ключевые слова)
При возникновении ошибки максимально точно её сформулируйте (и обязательно выложите лог) и под спойлер прикрепите код скрипта.
Но предварительно попробуйте сами с ней разобраться, выполнив предложенные действия описанные под спойлером «Ошибки»
Напоминаю, тут не стол заказов. Автору в qms НЕ писать. Посты с просьбой собрать zip для «хххх» Recovery оффтоп
Сообщения, не относящиеся к теме обсуждения (оффтоп), удаляются без предупреждения
Возможности
- Добавление нескольких пользовательских/системных приложений «за один клик» (одним патчем).
- Добавление/удаление системных приложений без root прав и вспомогательных программ.
- Изменение прошивки (замена файлов, украшательства и т.д.).
- Обновление программы или прошивки.
- Переразметка памяти (обсуждения в другой теме)
- Получение root прав SuperUser, SuperSU, Magisk
Инструменты и файлы
Инструменты
- Установленный на телефоне кастомный рекавери (CWM/TWRP)
- NotePad++ (редактор с сохранением Unix формата)
- Zip_signer (подписчик архивов)
- Архиватор ZIP
- Файл-заготовка sample.zip (либо update-binary для ручной сборки)
Zip_signer.rar ( 13.28 КБ )
sample-patch.rar ( 4.77 МБ )
update-binary.rar ( 113.25 КБ ) - Дополнительные версии бинарника. binary_all.rar ( 649.36 КБ )
- Бинарники (архив/исходники)
Бинарники (исходники)
Исходники бинарника, основная ссылка:
https://android.google…ootable/recovery/+refs
выбираем к примеру «android-9.0.0_r18» , потом ищем папку «updater», в папке «updater» исходники бинарника
К примеру https://android.google…droid-9.0.0_r18/updater — можно глянуть все команды которые может выполнить бинари в андроид 9.0.0 (в файле install.cpp, в самом низу)
Программы | Скрипты для создания update.zip
Программы
Скрипты
- Собрать свой update.zip (из заготовки sample.zip)
- Подписать update.zip утилитой Zip_signer(Не обязательно!)
- Закинуть на флэшку и установить в аппарат через ClockWorkMod Recovery
- Разархивировать архив sample.zip
- Удалить файлы подписи META-INF/CERT.RSA, CERT.SF, MANIFEST.MF (т.к. 2м шагом мы их будем создавать для своей сборки)
- Поместить в папку /data/app свое пользовательское приложение (xxxxx.apk)
- При необходимости отредактировать файл updater-script (подробнее позже)
- Заархивировать всё (META-INF и data) ZIP’ом без сжатия
- Переименовать Ваш отредактированный (т.е. уже с приложением внутри) sample.zip в update.zip
- Поместить его в папку с программой Zip_signer
- Запустить файл zip_signer.bat
- Дождаться, пока процесс будет завершен
- В папке появится файл update-finished.zip — это и есть подписанный файл
- Переименовать update-finished.zip по своему усмотрению (согласно логике патча)
- Перекинуть (переименованный) update-finished.zip на флэшку и установить его в аппарат через TWRP или CWM (install zip from sdcard -> chooze zip from internal sdcard -> Yes, install sample.zip)
- Перезагрузить аппарат
Создание в Linux
- Скачиваем signapk.zip и разархивируем в папку
- Назначаем права для всего содержимого — «rwxrwxrwx» (chmod -R 777 ~/)
- Выполняем программу подписи (signapk )
Внимание! Патчи создаются только для мод.рекавери и результативно работают только в них. В стоковых рекавери (на аппаратах «из коробки») патчи не работают.
Структура патча | Редактирование update-script
- папка META-INF
- папка источник установки приложений (system, data, sdcard, cache, sd-ext)
Обязательные файлы: - META-INF/com/google/android/update-binary — системное средство запуска данного патча, также создает временную рабочую папку tmp
- META-INF/com/google/android/updater-script — выполняемый скрипт по которому и происходят операции копирования и т.д.
Редактирование
Разберем sample.zip
Патч добавляет пользовательское приложение MyPiano в Data.
ui_print(«=== Patching new application == post-block code box»>
run_program(«/sbin/busybox», «mount», «/data»);
— (Монтирует data) открывает доступ для работы с системным разделом.
package_extract_dir(«data», «/data»);
— Копирует содержимое папки data в соответствующую папку на устройстве.
set_perm_recursive(1000, 1000, 0771, 0644, «/data/app»);
— Устанавливает владельца, группу и разрешения для содержимого папки на устройстве (инфо по коду ниже)
run_program(«/sbin/busybox», «umount», «/data»);
— Размонтирование data.
set_perm_recursive(1000, 1000, 0771, 0644, «/data/app/»);
можно заменить на:
set_perm(1000, 1000, 0644, «/data/app/mypiano.apk»);
delete(«/system/app/OldApk.apk»);
При условии что busybox находится в другом месте, возможная замена
run_program(«/sbin/busybox», «mount», «/data»);
run_program(«/system/xbin/busybox», «mount», «/data»);
mount(«ext4», «EMMC», «/dev/block/mmcblk0p5», «/data»);
Пример-пояснение
Сначала это вырабатывается как привычка, а в дальнейшем при просмотре сложного кода — очень облегчает «чтение» кода, поиск необходимой информации, наглядность разделов/этапов кода.
В примере простенький скрипт, в котором основные рабочие функции выделены отступом. Т.е. все остальные попросту для красоты и удобства (их можно даже удалить).
Также возможно использование двойных и тройных TAB’ов, наглядный пример — написание кода сайтов html.
show_progress(1.000000, 2);
ui_print(» «);
ui_print(«======================================= ———- Silent AUDIO Patch ———-«);
ui_print(«======================================= > Mounting system. «);
run_program(«/sbin/busybox», «mount», «/system»);
ui_print(«> Copying files. «);
package_extract_dir(«system», «/system»);
ui_print(«> Fixing permissions. «);
set_perm_recursive(0, 0, 0755, 0644, «/system/media/»);
ui_print(«> Unmounting system. «);
run_program(«/sbin/busybox», «umount», «/system»);
ui_print(«——- Changing AUDIO Complete ———«);
ui_print(» «);
Описание команд updater-script | Примеры использования команд
• package_extract_dir
Синтаксис: package_extract_dir(«», «»);
Копирует содержимое в . Файлы в имеющиеся в перезаписываются.
Пример: package_extract_dir(«system», «/system»); Скопирует файлы из папки update.zip/system в /system
• package_extract_file
Синтаксис: package_extract_file(«», «»);
Копирует файл в . Если файл существует, то он перезаписывается.
Пример: package_extract_file(«test.sh», «/tmp/test.sh»); Скопирует файл test.sh из update.zip в /tmp/test.sh
• format
Синтаксис: format(«MTD», «»);
Форматирует раздел (см. приложение).
Пример: format(«MTD», «system»); Полностью отформатирует /system . Примечание: форматирование удаляет данные необратимо.
Пример 2: format(«ext4», «EMMC», «/dev/block/mtdblock5», «0», «/system»);
Определение номера блока под спойлером «инфо и материалы».
• delete
Синтаксис: delete(«»[, «file2», . «fileN»]);
Удаляет файл(ы)
Пример: delete(«/system/app/Calculator.apk»); Удалит Calculator.apk из папки system/app.
• delete_recursive
Синтаксис: delete_recursive(«»[, «dir2», . «dirN»]);
Рекурсивно удаляет папку(и) со всем содержимым
Пример: delete_recursive(«/data/dalvik-cache»); Удалит папку /data/dalvik-cache со всем содержимым.
• run_program
Синтаксис: run_program(«»[, «», «», «»]);
Запускает программу(скрипт) .
Пример: run_program(«/tmp/install_busybox.sh»); Запустит скрипт /tmp/install_busybox.sh.
• set_perm
Синтаксис: set_perm(, , , «»[, . «pathtofileN»]);
Устанавливает владельца, группу и разрешения для файла или папки, как ‘chmod’, ‘chown’, и ‘chgrp’ всё в одном
Пример: set_perm(0, 2000, 0550, «/system/etc/init.goldfish.sh»); Установит владельца, группу и разрешения для файла /system/etc/init.goldfish.sh
• set_perm_recursive
Синтаксис: set_perm_recursive(, , , , «»[, . «»])
Рекурсивно устанавливает владельца, группу и разрешения для содержимого папки. — для папок, — для файлов.
Пример: set_perm_recursive(0, 0, 0755, 0644, «/system/app»); Установит права для содержимого /system/app, для папок — 0755, для файлов — 0644.
• show_progress
Синтаксис: show_progress(, );
Продвижение прогрессбара на долю за секунд. может быть нулевым для продвижения его по командe set_progress, а не по времени.
Пример: show_progress(0.100000, 1); Увеличит прогресс на 0.1 часть за 1 секунду
• set_progress
Синтаксис: set_progress();
Устанавливает положение прогрессбара на долю , для самого последнего вызова команды show_progress.
Пример: set_progress(0.500000);
• symlink
Синтаксис: symlink(«», «
Создает символическую ссылку (как ‘ln-s’). пишется в формате root:path, а в формате целевой файловой системы (и может быть относительным). Википедия Symlink.
Пример: symlink(«/data/app_s», «/system/app»); Создаст символическую ссылку на папку /data/app_s для папки /system/app
• mount
Синтаксис: mount(«», «», «»);
Монтирует в путь . должно быть название раздела, если это «MTD», или блок памяти если это «vfat»
Пример: mount(«MTD», «userdata», «/data»);
• unmount
Синтаксис: unmount(«»);
Отключает .
Пример: unmount(«/data»);
• ui_print
Синтаксис: ui_print(«»);
Выводит на экран сообщение
Пример: ui_print(«Formatting SYSTEM. «);
• sleep
Синтаксис: sleep();
Пауза процесса на секунд
Пример: sleep(5); — пауза 5 секунд, после чего код скрипта выполняется дальше.
Команды android 4.4+
• set_metadata / set_metadata_recursive
Синтаксис: set_metadata (. );
Устанавливает владельца, группу и разрешения (новая команда взамен set_perm для andriod 4.4.*)
Примеры: Android update-script (Пост #32151495)
Создание патча update.zip для прошивки через рекавери (Пост kory-vadim #81945464)
• set_metadata / set_metadata_recursive
Синтаксис:
set_metadata(«имя файла», «ключ1», «значение1», «ключ2», «значение2», . )
set_metadata_recursive(«имя директории», «ключ1», «значение1», «ключ2», «значение2», . )
Ключи:
* uid
* gid
* mode (set_perm_extd only)
* fmode (set_perm_extd_recursive only)
* dmode (set_perm_extd_recursive only)
* selabel
* capabilities
первые три (uid, gid, mode) это тоже самое что и в chmod, заполняется «uid», 0, «gid», 1000, «mode», 06754.
для установки прошивки хватает трех ключей «uid», 0, «gid», 1000, «mode», 06754.
Пример: set_metadata(«/system/xbin/shelld», «uid», 0, «gid», 1000, «mode», 06754, «capabilities», 0x0, «selabel», «u:object_r:system_file:s0»);
set_metadata_recursive(«/system/xbin», «uid», 0, «gid», 2000, «dmode», 0755, «fmode», 0755, «capabilities», «0x0», «selabel», «u:object_r:system_file:s0»);
• команды для Nexus’ов
block_image_update(«/dev/block/platform/msm_sdcc.1/by-name/system», package_extract_file(«system.transfer.list»), «system.new.dat», «system.patch.dat»);
Синтаксис: block_image_update(«Путь к блоку раздела», package_extract_file(«список информации для патча (?) «), «образ», «патч образа»);
я так понимаю, что так прошивается сильно сжатая прошивка (образ системы).
Еще ifelse
Пример: ifelse(is_mounted(«/system»), unmount(«/system»)); — если раздел сустем смонтирован дается команда на его размонтирование, если размонтиовать то нечего не происходит.
• Информация по атрибутам set_metadata и подобным командам на Android 4.4+
Android update-script (Пост blackeangel #50803606)
Описание откуда берутся «u:object_r:uncrypt_exec:s0» и подобные атрибуты. . .
• Пример скрипта который может удалять\перемещать\бекапить файлы и вести лог действий
Android Script Creator (Пост Octanium #51085030)
• Временный Busybox
временный busybox
Используется при отсутствии busybox, либо чтоб не привязываться к его расположению в системе.
package_extract_file(«busybox», «/tmp/busybox»);
set_perm(0, 0, 0777, «/tmp/busybox»);
run_program(«/tmp/busybox», «mount», «/data»);
.
run_program(«/tmp/busybox», «unmount», «/data»);
• Команды перезагрузки
перезагрузка
Код «перезагрузки» и «перезагрузки в рекавери» соответственно: