- Что такое umask и как установить права на файл или директорию
- Что такое umask?
- Как установить umask по умолчанию?
- Что такое umask равное 0022 и 0002?
- Итоги
- Калькулятор umask
- What is Umask in Linux
- How can we calculate UMASK in Linux?
- Display current umask value
- How can we set umask with Symbolic Values?
- What are the Limitations of umask?
- Conclusion
- Linux umask command
- Description
- Syntax
- Options
- What are permissions, and how do they work?
- How are permissions represented?
- Specifying the file creation mask using symbols
- Specifying the file creation mask using numeric representation
- The other permission digit
- So how does the umask actually work?
- Examples
- Related commands
Что такое umask и как установить права на файл или директорию
Очередной пост из серии «Ликбез». Всегда хотел это понять, но вечно что-то мешало.
Подглядел вот здесь, довольно легкое и доходчивое объяснение (прошу не путать ликбез с академическим толкованием) того, как посчитать umask, если знаешь какие права в итоге должен иметь твой файл или директория. Как правило, при администрировании Linux систем, нам больше всего приходится сталкиваться с фактическими правами, а вот с umask возникают некоторые трудности. Автор оригинальной статьи сам немного запутался, но я все исправил.
Что такое umask?
При создании файла или директории, среда операционной системы присваивает им определенные права доступа по умолчанию, и umask — это пользовательская маска (user mask), которая используется для определения конечных прав доступа.
Как установить umask по умолчанию?
Сперва, нам необходимо понять, как узнать текущее значение нашей umask. Сделать это очень просто:
Umask для всех пользователей по умолчанию устанавливается в файлах /etc/.bashrc или /etc/.profile.
После процедуры начальной инсталляции Linux, по умолчанию она равна 0022 (022) или 0002 (002).
Если в этих файлах, мы просто добавим или изменим строку с umask:
То при следующем входе мы получим новое значение umask. Если выполним эту команду в текущем сеансе, то, соответственно, изменим значение для маски на время работы сеанса.
Что такое umask равное 0022 и 0002?
В операционной системе Linux базовые права для директории равны 0777 (rwxrwxrwx), а для файла 0666 (rw-rw-rw).
По умолчанию umask 0002 используется для обычного пользователя. С этой маской права по умолчанию, для директории, равны 775, а для файла 664.
Для суперпользователя (root) umask по умолчанию равна 0022. С этой маской права по умолчанию, для директории, равны 755, а для файла 644.
Как посчитать (определить) права файла для маски 022 (пользователь root):
Права по умолчанию: 666
Вычитаемое значение umask: 022 (-)
Итоговые права: 644
Как посчитать (определить) права директории для маски 022 (пользователь root):
Права по умолчанию: 777
Вычитаемое значение umask: 022 (-)
Итоговые права: 755
Итоги
Таким образом: umask «отбирает» необходимые права в нужных разрядах: 7-ка полностью все, 2-ка права на запись, 0 оставляет по умолчанию. По-моему очень просто и понятно.
К примеру вот такие команды:
приведут к такому результату:
И напоследок, пример umask с различными (наиболее часто используемыми) значениями и результирующие (итоговые) права:
Значение umask | Файл | Директория | ||||||
---|---|---|---|---|---|---|---|---|
Итог | Владелец | Группа | Остальные | Итог | Владелец | Группа | Остальные | |
0000 | 666 | rw- | rw- | rw- | 777 | rwx | rwx | rwx |
0002 | 664 | rw- | rw- | r— | 775 | rwx | rwx | r-x |
0022 | 644 | rw- | r— | r— | 755 | rwx | r-x | r-x |
0007 | 660 | rw- | rw- | — | 770 | rwx | rwx | — |
0077 | 600 | rw- | — | — | 700 | rwx | — | — |
0027 | 640 | rw- | r— | — | 750 | rwx | r-x | — |
0277 | 400 | r— | — | — | 500 | r-x | — | — |
Калькулятор umask
Конечно-же, ограниченный упрощенный метод подсчета и приведенная таблица не способны покрыть множество вариантов значений umask, поэтому, для более полной и четкой картины, предлагаю вам воспользоваться следующим наглядным инструментом:
«Онлайн umask калькулятор»
Источник
What is Umask in Linux
UMASK in Linux and Unix systems is actually known as User Mask or it is also called User File creation MASK. This is a kind of base permission or default permission given when a new file or folder is created in the Linux box.
Most of the distribution of Linux gives 022 as default UMASK. We can say, it is default permissions to the file and folders by the system. When we create any file or directory in Linux, they are governed by umask setting.
In case, any system administrator does not set the default umask will be 0000 . This means that the new files created will have read and write permissions for each user and new directories will have read, write and execute permissions.
How can we calculate UMASK in Linux?
One thing is umask value is generally the same for files and folders but the calculation of these values based on the permissions on files and directories are different.
Minimum UMASK value for directory: 000 and Maximum: 777
Minimum UMASK value for file: 000 and Maximum: 666
Here, the reason for keeping the maximum value 666 for files is because script files and binary files in Linux should only have execute permissions. Normal files in Linux should only have read and write permissions. Normally, umask is calculated through bitwise AND operator. Some of the common octal notations are:
Now, we can easily make use of the above mentioned table to calculate permission for files. For instance, if an umask is set to 077 means the permission is generally calculated as below:
To set the above umask, you should type the command
Display current umask value
If you run umask command without any argument it will display the current mask value.
How can we set umask with Symbolic Values?
Below mentioned are the symbolic values we can use:
r : read, w : write, x : execute, u : user ownership, g : group ownership and o : other ownership
What are the Limitations of umask?
1. umask command can be used to restrict permissions.
2. We can’t grant additional permissions beyond what is normally specified by any program used to create files and folders. If you want to make changes then you should use chmod command instead.
3. Many operating systems do not have a file that should be created with execute permission. In such environments, the new files will always have execute permissions disabled.
4. Mask is only applied to those functions which creates a new file.
Conclusion
In this tutorial we learned what is umask in linux and command to set new umask value. I hope you enjoyed reading and for more information refer umask man pages.
Источник
Linux umask command
On Unix-like operating systems, the umask command returns, or sets, the value of the system’s file mode creation mask.
This page covers the Linux version of umask.
Description
On Linux and other Unix-like operating systems, new files are created with a default set of permissions. Specifically, a new file’s permissions may be restricted in a specific way by applying a permissions «mask» called the umask. The umask command is used to set this mask, or to show you its current value.
Syntax
Options
-S | Accept a symbolic representation of a mask, or return one. |
mask | If a valid mask is specified, the umask is set to this value. If no mask is specified, the current umask value is returned. |
What are permissions, and how do they work?
As you may know, each file on your system has associated with it a set of permissions used to protect files: a file’s permissions determine which users may access that file, and what type of access they have to it.
There are three general classes of users:
- The user who owns the file («User«).
- Users belonging to the file’s defined ownership group («Group«).
- Everyone else («Other«).
In turn, for each of these classes of user, there are three types of file access:
- The ability to look at the contents of the file («Read«).
- The ability to change the contents of the file («Write«).
- The ability to run the contents of the file as a program on the system («Execute«).
So, for each of the three classes of user, there are three types of access. Taken together, this information makes up the file’s permissions.
How are permissions represented?
There are two ways to represent a file’s permissions: symbolically (using symbols like «r» for read, «w» for write, and «x» for execute) or with an octal numeric value.
For example, when you list the contents of a directory at the command line using the ls command as follows:
you will see (among other information) the file permission information for each file. Here, it is represented symbolically, which looks like the following example:
There are ten symbols here. The first dash («—«) means that this is a «regular» file, in other words, not a directory (or a device, or any other special kind of file). The remaining nine symbols represent the permissions: rwxr-xr—. These nine symbols are actually three sets of three symbols each, and represent the respective specific permissions, from left to right:
symbols | meaning |
---|---|
rwx | the file’s owner may read, write, or execute this file as a process on the system. |
r-x | anyone in the file’s group may read or execute this file, but not write to it. |
r— | anyone at all may read this file, but not write to it or execute its contents as a process. |
Specifying the file creation mask using symbols
The general symbolic form of a mask is as follows:
permission symbol is any combination of r (read), w (write), or x (execute), as described above.
user class symbol may be one or more of the following:
u | User (the owner of the file). |
g | Group (any member of the file’s defined group). |
o | Other (anyone else). |
a | All (equivalent to ugo). |
permissions operator may be one of the following:
+ | allow the specified file permissions to be enabled for the specified user classes (permissions that are not specified are unchanged in the mask). |
— | prohibit the specified file permissions from being enabled for the specified user classes (permissions that are not specified are unchanged in the mask). |
= | allow the specified file permissions to be enabled for the specified user classes (permissions not specified will be prohibited by the mask during file creation). |
So, for example, the following umask command:
sets the mask so that when files are created, they have permissions which allow write permission for the user (file owner). The rest of the file’s permissions would be unchanged from the operating system default.
Multiple changes can be specified by separating multiple sets of symbolic notation with commas (but not spaces!). For example:
This command sets the mask so that when subsequent files are created, they have permissions that:
- prohibit the execute permission from being set for the file’s owner (user), while leaving the rest of the owner permissions unchanged;
- enable read permission for the group, while prohibiting write and execute permission for the group;
- enable write permission for others, while leaving the rest of the other permissions unchanged.
Note that if you use the equals operator («=«), any permissions not specified will be specifically prohibited. For example, the command
Sets the file creation mask so that new files are inaccessible to everyone.
Specifying the file creation mask using numeric representation
The file creation mask can also be represented numerically, using octal values (the digits from 0 to 7). When using octal numeric representation, certain numbers represent certain permissions, and these numbers are added or subtracted from each other to represent the final, combined permissions value. Specifically, the numbers 1, 2, and 4 represent the following permissions:
number | permission |
---|---|
4 | read |
2 | write |
1 | execute |
These numbers are used because any combination of these three numbers will be unique. The following table illustrates their unique combinations:
read value + | write value + | execute value = | combined value: | symbolic equivalent: |
---|---|---|---|---|
0 | 0 | 0 | 0 | |
0 | 0 | 1 | 1 | x |
0 | 2 | 0 | 2 | w |
0 | 2 | 1 | 3 | wx |
4 | 0 | 0 | 4 | r |
4 | 0 | 1 | 5 | rx |
4 | 2 | 0 | 6 | rw |
4 | 2 | 1 | 7 | rwx |
For each class of user, one digit can represent their permissions; using the example above, we could represent the symbolic permission of rwxr-xr— using the three-digit octal number 754. The order of the digits is always the same: User, Group, Other.
The other permission digit
In octal representations of file permissions, there are actually four digits. The three important digits we’ve discussed are the last three digits. The first digit is a special file permission indicator, and for this discussion can be considered always to be zero. So from here on out, when we discuss file permission 777, it may also be referred to as 0777.
So how does the umask actually work?
The umask masks permissions by restricting them by a certain value.
Essentially, each digit of the umask is «subtracted» from the OS’s default value to arrive at the default value you define. It’s not really subtraction; technically, the mask is negated (its bitwise compliment is taken) and this value is then applied to the default permissions using a logical AND operation. The result is that the umask tells the operating system which permission bits to «turn off» when it creates a file.
In Linux, the default permissions value is 666 for a regular file, and 777 for a directory. When creating a new file or directory, the kernel takes this default value, «subtracts» the umask value, and gives the new files the resulting permissions.
This table shows how each digit of the umask value affects new file and directory permissions:
umask digit | default file permissions | default directory permissions |
---|---|---|
0 | rw | rwx |
1 | rw | rw |
2 | r | rx |
3 | r | r |
4 | w | wx |
5 | w | w |
6 | x | x |
7 | (no permission allowed) | (no permission allowed) |
So if our umask value is 022, then any new files will, by default, have the permissions 644 (666 — 022). Likewise, any new directories will, by default, be created with the permissions 755 (777 — 022).
Examples
To view your system’s current umask value, enter the command:
which returns your system’s umask as a four-digit octal number, for example:
Again, the first zero is a special permission digit and can be ignored; for our purposes, 0002 is the same as 002.
To view this as a symbolic representation, use the -S flag:
Which returns the same value symbolically, for example:
where u stands for user, g stands for group, and o stands for other. This is telling us the So if we create a new file, it has the default permissions 664, which is 666 (the default permissions for files) masked by 002 (our umask value).
Let’s test this by creating a new file with the touch command:
And now let’s get a directory listing for that file:
As expected, the new file has permissions -rw-rw-r—, or 0664: The owner and group may read or write the file, and others may only read it.
Now let’s change the umask. To set a umask of 022, use the command:
This is the same as running umask 0022; if you specify only three digits, the first digit will be assumed to be zero. Let’s verify that the change took place:
And now let’s create a new file:
And now let’s view its directory listing, with the first file we created, using the asterisk wildcard («*«) to view all files whose name start with «testfile«:
As you can see, testfile2 has the permissions 644.
Here are some other example umask commands:
Sets the mask so that new files allows all users to read them; other permissions will be unchanged from the default.
Sets the mask so that new files will not initially be executable by any user; other default permissions unchanged from defaults.
Sets the mask so that new files will be readable and writable by the user who owns the file, but may not be executed; group members and others have no permissions to access the file.
Make new files inaccessible to everyone — no one can read, write, or execute them.
Make new files completely accessible (read, write, and execute) to absolutely everyone. However, this is a bad idea. Don’t do this.
Related commands
chmod — Change the permissions of files or directories.
csh — The C shell command interpreter.
ksh — The Korn shell command interpreter.
sh — The Bourne shell command interpreter.
Источник