Windows Tips - The icacls command

icacls - 用于显示或修改指定文件上的可自由支配访问控制列表,并将存储的可自由支配访问控制列表应用于指定目录中的文件

Displays or modifies discretionary access control lists (DACLs) on specified files, and applies stored DACLs to files in specified directories

  • Usage
ICACLS name /save aclfile [/T] [/C] [/L] [/Q]
    stores the DACLs for the files and folders that match the name
    into aclfile for later use with /restore. Note that SACLs,
    owner, or integrity labels are not saved.

ICACLS directory [/substitute SidOld SidNew [...]] /restore aclfile
                 [/C] [/L] [/Q]
    applies the stored DACLs to files in directory.

ICACLS name /setowner user [/T] [/C] [/L] [/Q]
    changes the owner of all matching names. This option does not
    force a change of ownership; use the takeown.exe utility for
    that purpose.

ICACLS name /findsid Sid [/T] [/C] [/L] [/Q]
    finds all matching names that contain an ACL
    explicitly mentioning Sid.

ICACLS name /verify [/T] [/C] [/L] [/Q]
    finds all files whose ACL is not in canonical form or whose
    lengths are inconsistent with ACE counts.

ICACLS name /reset [/T] [/C] [/L] [/Q]
    replaces ACLs with default inherited ACLs for all matching files.

ICACLS name [/grant[:r] Sid:perm[...]]
       [/deny Sid:perm [...]]
       [/remove[:g|:d]] Sid[...]] [/T] [/C] [/L] [/Q]
       [/setintegritylevel Level:policy[...]]

    /grant[:r] Sid:perm grants the specified user access rights. With :r,
        the permissions replace any previously granted explicit permissions.
        Without :r, the permissions are added to any previously granted
        explicit permissions.

    /deny Sid:perm explicitly denies the specified user access rights.
        An explicit deny ACE is added for the stated permissions and
        the same permissions in any explicit grant are removed.

    /remove[:[g|d]] Sid removes all occurrences of Sid in the ACL. With
        :g, it removes all occurrences of granted rights to that Sid. With
        :d, it removes all occurrences of denied rights to that Sid.

    /setintegritylevel [(CI)(OI)]Level explicitly adds an integrity
        ACE to all matching files.  The level is to be specified as one
        of:
            L[ow]
            M[edium]
            H[igh]
        Inheritance options for the integrity ACE may precede the level
        and are applied only to directories.

    /inheritance:e|d|r
        e - enables inheritance
        d - disables inheritance and copy the ACEs
        r - remove all inherited ACEs


Note:
    Sids may be in either numerical or friendly name form. If a numerical
    form is given, affix a * to the start of the SID.

    /T indicates that this operation is performed on all matching
        files/directories below the directories specified in the name.

    /C indicates that this operation will continue on all file errors.
        Error messages will still be displayed.

    /L indicates that this operation is performed on a symbolic link
       itself versus its target.

    /Q indicates that icacls should suppress success messages.

    ICACLS preserves the canonical ordering of ACE entries:
            Explicit denials
            Explicit grants
            Inherited denials
            Inherited grants

    perm is a permission mask and can be specified in one of two forms:
        a sequence of simple rights:
                N - no access
                F - full access
                M - modify access
                RX - read and execute access
                R - read-only access
                W - write-only access
                D - delete access
        a comma-separated list in parentheses of specific rights:
                DE - delete
                RC - read control
                WDAC - write DAC
                WO - write owner
                S - synchronize
                AS - access system security
                MA - maximum allowed
                GR - generic read
                GW - generic write
                GE - generic execute
                GA - generic all
                RD - read data/list directory
                WD - write data/add file
                AD - append data/add subdirectory
                REA - read extended attributes
                WEA - write extended attributes
                X - execute/traverse
                DC - delete child
                RA - read attributes
                WA - write attributes
        inheritance rights may precede either form and are applied
        only to directories:
                (OI) - object inherit
                (CI) - container inherit
                (IO) - inherit only
                (NP) - don't propagate inherit
                (I) - permission inherited from parent container

Examples:

        icacls c:\windows\* /save AclFile /T
        - Will save the ACLs for all files under c:\windows
          and its subdirectories to AclFile.

        icacls c:\windows\ /restore AclFile
        - Will restore the Acls for every file within
          AclFile that exists in c:\windows and its subdirectories.

        icacls file /grant Administrator:(D,WDAC)
        - Will grant the user Administrator Delete and Write DAC
          permissions to file.

        icacls file /grant *S-1-1-0:(D,WDAC)
        - Will grant the user defined by sid S-1-1-0 Delete and
          Write DAC permissions to file.
  • 锁定目录
@echo off
 
if "%1"=="reset" (
    for /R %%f in (*.*) do icacls "%%f" /reset
) else (
    for /R %%f in (*.*) do (
        icacls "%%f" /deny "Administrators":DW
        icacls "%%f" /deny "Authenticated Users":DW
    )
)
  • 仅授权文件给所有者

SSH通过私钥登陆远程服务器的时候,会检查私钥的访问权限,在Ubuntu下,仅当前用户可访问的私钥才会继续,而Windows OpenSSH也有相应的要求。

未经处理的私钥登陆会提示如下错误:

$ ssh -i .\.ssh\my-ssh-key username@my-host-name
The authenticity of host 'my-host-name (1.2.3.4)' can't be established.
ECDSA key fingerprint is SHA256:1hHfC5NGoXdTYEApx2SsLwUjneWV90+UakcdNxZGPh8.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'my-host-name,1.2.3.4' (ECDSA) to the list of known hosts.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions for '.\\.ssh\\my-ssh-key' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
Load key ".\\.ssh\\my-ssh-key": bad permissions
username@my-host-name: Permission denied (publickey).

由于Windows文件系统并没有类似于UNIX文件系统的rwx控制方式,所以是通过文件权限访问的方式来间接实现的,相应的Windows命令就是cacls.exe,为了便利操作,下面提供了Powershell的脚本以方便调用:

<#
//------------------------------------------------------------------------------
// Function: cacls_to_owner_only
// Change the file access permissions to owner only
//------------------------------------------------------------------------------
#>
function cacls_to_owner_only($file)
{
    if ([System.IO.File]::Exists($file)) {
        $cmds = @(
            "icacls.exe ""$file"" /c /t /inheritance:d",
            "icacls.exe ""$file"" /c /t /grant ${Env:USERNAME}:F",
            "icacls.exe ""$file"" /c /t /remove Administrator BUILTIN\Administrators BUILTIN Everyone System Users ""Authenticated Users"""
        )
        foreach ($cmd in $cmds) {
            Write-Host $cmd
            iex $cmd
            Write-Host ""
        }
    }
    else {
        Write-Error "File not found: ``$file``"
    }
}

调用该函数处理私钥:

$ cacls_to_owner_only .\.ssh\my-ssh-key
icacls.exe ".\.ssh\my-ssh-key" /c /t /inheritance:d
processed file: .\.ssh\my-ssh-key
Successfully processed 1 files; Failed processing 0 files

icacls.exe ".\.ssh\my-ssh-key" /c /t /grant username:F
processed file: .\.ssh\my-ssh-key
Successfully processed 1 files; Failed processing 0 files

icacls.exe ".\.ssh\my-ssh-key" /c /t /remove Administrator BUILTIN\Administrators BUILTIN Everyone System Users "Authenticated Users"
processed file: .\.ssh\my-ssh-key
Successfully processed 1 files; Failed processing 0 files