Windows 10 chmod 600

Команда chmod: как поменять права доступа к файлам и директориям

Какие бывают права доступа к файлам в Linux

Для всех файлов и директорий Linux устанавливаются следующие права доступа:

  • разрешение чтение содержимого файла
  • разрешение на изменение содержимого файла
  • разрешение на исполнение файла

Эти три разрешения устанавливаются отдельно для следующих групп:

  • владелец файла
  • группа владельцев файла, к которой он принадлежит
  • все остальные

Подробности о владельце файла и о том, как его поменять, смотрите в статье «Как пользоваться командой chown для смены владельца и группы файла в Linux».

Условные обозначения прав доступа и пользователей в chmod

Чтобы изменить режим (права доступа) файла или каталога, используется команда chmod. Имейте в виду, что только владелец файла или суперпользователь может изменить режим файла или каталога. chmod поддерживает два различных способа задания изменений режима: представление в восьмеричных числах или символьное представление. Сначала мы рассмотрим представление восьмеричных чисел.

Каждую восьмеричную цифру можно представить как три двоичные цифры. Три цифры соответствуют трём параметрам режима доступа: чтение, запись, выполнение. Поэтому права доступа можно представить в виде трёх двоичных цифр, которые можно записать как одну восьмеричную цифру.

Следующая таблица поможет вам понять, что имеется ввиду.

Восьмеричное число Двоичное число Файловый режим
0 000
1 001 —x
2 010 -w-
3 011 -wx
4 100 r—
5 101 r-x
6 110 rw-
7 111 rwx

Используя три восьмеричных цифры, мы можем установить режим файла для владельца, группы владельцев и всех остальных:

Передав аргумент «600», мы смогли установить разрешения владельца на чтение и запись, удалив при этом все разрешения группы владельца и всех остальных. Хотя запоминание восьмеричного бинарного отображения может показаться неудобным, вам обычно нужно использовать только несколько часто используемых: 7 (rwx), 6 (rw-), 5 (r-x), 4 (r—) и 0 (—).

Либо можно запомнить значение одиночных прав доступа и складывать их значения для получения любых комбинаций: 4 (r—), 2 (-w-), 1 (—x). После того, как вы их запомнили, можно получить любую комбинацию, для прав чтения и записи это 6 (4+2) (rw-), для прав записи и выполнения это 3 (2+1) (-wx), для прав чтения и выполнения это 5 (4+1) (r-x)

chmod также поддерживает символическую запись для указания режимов файлов. Символическая запись делится на три части: на кого повлияет изменение, какая операция будет выполнена и какое разрешение будет установлено. Чтобы указать, на кого это влияет, комбинация символов «u», «g», «o» и «a» используется следующим образом:

Сокращение от «пользователь», но означает владельца файла или каталога.

Сокращение от «других», но означает все остальные.

Сокращено от «все». Сочетание «u», «g» и «o».

Если символ не указан, будет принято «все». Операция может быть «+», указывающим, что разрешение должно быть добавлено, «», указывающим, что разрешение должно быть удалено, или «=», указывающим, что должны применяться только указанные разрешения, и что все остальные должны быть удалены.

Права доступа указываются символами «r», «w» и «x». Вот несколько примеров символической записи:

Символ Значение
u
Обозначение Значение
u+x Добавить разрешение на выполнение для владельца.
u-x Удалить разрешение на выполнение от владельца.
+x Добавить разрешение на выполнение для владельца, группы и всех остальных. Эквивалент a+x.
o-rw Удалить права на чтение и запись у любого пользователя, кроме владельца и группы владельцев.
go=rw Установить для группы владельцев и всех, кроме владельца, права на чтение и запись. Если владелец группы или все остальные ранее имели разрешения на выполнение, эти разрешения удаляются.
u+x,go=rx Добавить разрешение на выполнение для владельца и установить разрешения на чтение и выполнение для группы и других пользователей. Несколько записей могут быть разделены запятыми.

Некоторые люди предпочитают использовать восьмеричные обозначения, некоторые люди любят символические. Символьная нотация даёт преимущество, заключающееся в том, что вы можете установить один атрибут, не мешая другим.

Как рекурсивно поменять права доступа в chmod

Для рекурсивного изменения прав доступа используйте опцию -R.

Предостережение в отношении опции «—recursive»: она действует как для файлов, так и для каталогов, поэтому она не так полезна, как можно было бы надеяться, поскольку мы редко хотим, чтобы файлы и каталоги имели одинаковые разрешения.

Как скопировать права доступа с файла на другие файлы

Если вам нужно установить точно такие же права доступа, как и у другого файла, то используйте опцию —reference=ФАЙЛ_ОБРАЗЕЦ. В этом случае вместо указанного РЕЖИМА, будут установлены права доступа такие же, как и у указанного ФАЙЛА_ОБРАЗЦА.

Chmod/Chown WSL Improvements

January 12th, 2018

We’ve added new file system features to WSL in Insider Build 1706 3 . You can now set the owner and group of files using chmod/chown and modify read/write/execute permissions in WSL. You can also create special files like fifos, unix sockets, and device files. We’re introducing new mounting options with DrvFs for projecting permissions onto files alongside providing new Linux metadata on files and folders.

There’s one step you must take before you can enjoy these new features : you must unmount drvfs and remount it with the ‘metadata’ flag. To do this:

sudo umount /mnt/c sudo mount -t drvfs C: /mnt/c -o metadata

You can verify that it mounted correctly by running “mount -l” to see the output below:

What is DrvFs?

DrvFs is a filesystem plugin to WSL that was designed to support interop between WSL and the Windows filesystem. DrvFs enables WSL to mount drives with supported file systems under / mnt , such as / mnt /c, / mnt /d, etc.

You can learn more about DrvFs and the WSL filesystem in a previous blog post from June 2016, WSL File System Support , which covers the Linux filesystem as it pertains to WSL and compares it to the Windows filesystem.

Let’s take a look at the two new features in detail. A nd remember, some of the functionality discussed below already exists on the Linux filesystem side—bringing this over to the Windows side is what’s new.

Support for Additional Metadata

Linux permissions are added as additional metadata to the file. This means a file can have Linux *and *Windows read/write/execute permission bits.

How did permissions work in the past?

Prior to Build 17063, all files/folders list “root” as the owner and belonged to the group “root”. The permission bits on each file/folder was derived from Windows permissions–no write bit checked for Windows meant no write bit set in WSL.

Additionally, attempting to chmod or chown on a file/folder resulted in a no-op (they wouldn’t do anything!)

How do permissions work now?

For files that don’t have metadata, we apply the same approach as what is described in pre-17063 builds. But now, chmod/chown can assign metadata to the file or folder. Newly created files in WSL will be created with metadata by default and will respect the mount options you’ve set (discussed later) or the permissions you pass when executing a mkdir/open.

Once the file or folder has metadata, Windows and Linux permissions will not remain in lock-step with each other.

Important Caveats

There are a few things to make sure you’re aware of when tinkering with the new metadata:

  1. Editing a file using a Windows editor may remove the file’s Linux metadata. In this case, the file will revert to its default permissions
  2. Removing all write bits on a file in WSL will make Windows mark the file as read-only.
  3. If you have multiple WSL distros installed or multiple Windows users with WSL installed, they will all use the same metadata on the same files. The uid’s of each WSL user account might differ. This something to consider when setting permissions.

For example, you can disable write permissions on a file in Windows and chmod the file to show write permissions are enabled in WSL. Or you can have read permissions enabled under Windows and remove read permissions in WSL. You can see this concept illustrated below.

In the example below, I remove a file’s write permissions in WSL which disables the ability to write changes to the file from WSL. But I can still open the file and write changes from Windows because I have the write permission set in Windows.

Inversely, if I have a file in WSL which states its Linux permissions allows writing–but I’ve disabled write permissions in Windows–I still won’t be able to perform actions. Windows permissions for a file or folder will trump the permissions set under WSL. You can see this concept illustrated below.

Special Files

You can create special files like fifos, unix sockets, and device files.

Mount Options

We’ve added new mount options to DrvFs to control permissions for files without metadata. Y ou can combine with the metadata option to specify default permissions for files without metadata. The new mount options include:

  • uid: the user ID used for the owner of all files
  • gid: the group ID used for the owner of all files
  • *umask : *an octal mask of permissions to exclude for all files and directories.
  • fmask: an octal mask of permissions to exclude for all regular files.
  • dmask: an octal mask of permissions to exclude for all directories.

A sample command using the mount options could look like this:

sudo mount -t drvfs C: /mnt/c -o metadata,uid=1000,gid=1000,umask=22,fmask=111

After executing the mount command, you will see your mount (in this case, C:) listed with all the parameters you passed in when querying for a list of mounted devices.

If you’re unfamiliar with octal masks, consult the man pages for chmod to learn more (in the WSL console, enter “man chmod “).

Mount Options Example

In my WSL instance, I have created a group called “metadatagroup” and a user named “msbob”. They have gid and uid values equal to 1001. I also have a file and folder without metadata in WSL. If I mount DrvFs with this command:

sudo mount -t drvfs C: /mnt/c -o metadata,uid=1001,gid=1001,umask=22,fmask=111

Take a peek at the permissions on the file and directory that did not previously have metadata. It was appropriately assigned msbob and metadatagroup for the owner and group bits, as expected.

Additionally, because we passed in umask=22 and fmask=111, our files and directories have had their read/write/execute permissions update accordingly. The umask used in this example will disable execution rights for files by default, which allows you to be more explicit in setting execution permissions on a file-by-file basis.

By default, WSL will set the uid and gid to the default user with drives that are auto-mounted during instance start. If you mount manually, you will have to set these explicitly (the default user that gets created when WSL is first installed has a uid=1000 and gid=1000).

What do you think about the latest changes to DrvFs ? Drop us a comment below or tweet at us!

chmod 600 on Windows? #132

Comments

DarwinJS commented Feb 25, 2016

win32-OpenSSH is giving the error «Permission denied (publickey)» when I try to use an amazon pem.

What is the windows equivalent icacls command for chmod 600? All I find on the net is work arounds by using other products — but I would like to use openssh.

The text was updated successfully, but these errors were encountered:

manojampalam commented Feb 27, 2016

Did you try it the UI way, Right-Click, properties, security.

jhudsoncedaron commented Mar 1, 2016

Ugh! A good case for shipping a command-line tool for fixing private key files.

Ventusfahrer commented Mar 1, 2016

. well the problem is that Windows is much more flexible in file system security than the common Unix implementations. chmod will never be enough for this job.

if you need to modify security settings per command line use calcs.exe or icacls.exe
. or in powershell Get-ACL/Set-ACL. search Google for examples.

If you need to investigate in file access related problems use procmon.exe (windows applicaton from www.sysinternals.com) on the desktop.

Ventusfahrer commented Mar 1, 2016

. the most important thing is to find out which process (running under a specific account) tries to access which file.
Depending where the file is located, it may have very special security settings mostly inherited by the parent directory. In some cases you are able to create a file but not to delete it.

Use procmon to find out what is happening

DarwinJS commented Mar 1, 2016

This is me running ssh to access the local ssh key file.

I understand how to use those tools, but they will not help me understand what this linux ported software expects to see for Windows permissions to equate to chmod 600.

Seems by now someone would have made a PowerShell CMDLet «chmod» that handles it for me.

Does anyone know exactly what perms ssh.exe is looking for on the key file?

jhudsoncedaron commented Mar 1, 2016

I think removing all access from the advanced view by unchecking inherit and deleting everything, then giving yourself full control does the needful.

altaurog commented Mar 2, 2016

Does the win32 port actually check file and directory permissions? It looks to me like it doesn’t. The functions secure_filename and auth_secure_path in auth.c both return 0 if compiled with WIN32_FIXME , which is defined in win32_config.h.

DarwinJS commented Mar 2, 2016

Not only that, but with the latest version I do not get the error — I must have misinterpreted the error.
Thanks.

DreaJulca commented Apr 28, 2018 •

A PowerShell/CMD «chmod 600» equivalent would be a really convenient help if, just to pull a totally random and impersonal example out of the air, someone needed to give owner permissions of a private key to NT AUTHORITY via PsExec while trying to use their desktop running Windows 10 Home as a personal server to give one or two fellow researchers access to to one’s pre-existing GPU installation of TensorFlow.

Of course, it’s possible that there is already a solution for this and I’m just not aware of it.

jhudsoncedaron commented Apr 30, 2018

I guess I’m used to the unix world bug where ssh doesn’t actually check the full ACL but only the classic permissions; hence DreaJulca’s scenario wouldn’t have broken it.

goldstar611 commented May 19, 2020

We have issues with adminstrators_authorized_keys as well but have found icacls to resolve inherited permissions with

Читайте также:  Использование windows 10 как сервера
Оцените статью