HEX
Server: Apache
System: Linux server2.voipitup.com.au 4.18.0-553.109.1.lve.el8.x86_64 #1 SMP Thu Mar 5 20:23:46 UTC 2026 x86_64
User: posscale (1027)
PHP: 8.2.30
Disabled: exec,passthru,shell_exec,system
Upload Files
File: //opt/saltstack/salt/lib/python3.10/site-packages/salt/utils/__pycache__/win_dacl.cpython-310.pyc
o

�N�g�~�@s�dZddlZddlZddlZddlmZmZdZzddl	Z	ddl
Z
ddlZddlZdZWn	e
y5Ynwe�e�ZdZdd�Zd5d	d
�Zd6dd�Zd
d�Zdd�Zdd�Zd7dd�Zd7dd�Zd7dd�Zd7dd�Z					d8dd�Zd9dd �Zd6d!d"�Z	d:d#d$�Z	d:d%d&�Z d;d'd(�Z!d7d)d*�Z"					d<d+d,�Z#d=d-d.�Z$								d>d/d0�Z%d1d2�Z&					d?d3d4�Z'dS)@a
============
Windows DACL
============

This salt utility contains objects and functions for setting permissions to
objects in Windows. You can use the built in functions or access the objects
directly to create your own custom functionality. There are two objects, Flags
and Dacl.

If you need access only to flags, use the Flags object.

.. code-block:: python

    import salt.utils.win_dacl
    flags = salt.utils.win_dacl.Flags()
    flag_full_control = flags.ace_perms['file']['basic']['full_control']

The Dacl object inherits Flags. To use the Dacl object:

.. code-block:: python

    import salt.utils.win_dacl
    dacl = salt.utils.win_dacl.Dacl(obj_type='file')
    dacl.add_ace('Administrators', 'grant', 'full_control')
    dacl.save('C:\temp')

Object types are used by setting the `obj_type` parameter to a valid Windows
object. Valid object types are as follows:

- file
- service
- printer
- registry
- registry32 (for WOW64)
- share

Each object type has its own set up permissions and 'applies to' properties as
follows. At this time only basic permissions are used for setting. Advanced
permissions are listed for displaying the permissions of an object that don't
match the basic permissions, ie. Special permissions. These should match the
permissions you see when you look at the security for an object.

**Basic Permissions**

    ================  ====  ========  =====  =======  =======
    Permissions       File  Registry  Share  Printer  Service
    ================  ====  ========  =====  =======  =======
    full_control      X     X         X               X
    modify            X
    read_execute      X
    read              X     X         X               X
    write             X     X                         X
    read_write                                        X
    change                            X
    print                                    X
    manage_printer                           X
    manage_documents                         X
    ================  ====  ========  =====  =======  =======

**Advanced Permissions**

    =======================  ====  ========  =======  =======
    Permissions              File  Registry  Printer  Service
    =======================  ====  ========  =======  =======
    *** folder permissions
    list_folder              X
    create_files             X
    create_folders           X
    traverse_folder          X
    delete_subfolders_files  X

    *** file permissions
    read_data                X
    write_data               X
    append_data              X
    execute_file             X

    *** common permissions
    read_ea                  X
    write_ea                 X
    read_attributes          X
    write_attributes         X
    delete                   X     X
    read_permissions         X               X        X
    change_permissions       X               X        X
    take_ownership           X               X
    query_value                    X
    set_value                      X
    create_subkey                  X
    enum_subkeys                   X
    notify                         X
    create_link                    X
    read_control                   X
    write_dac                      X
    write_owner                    X
    manage_printer                           X
    print                                    X
    query_config                                      X
    change_config                                     X
    query_status                                      X
    enum_dependents                                   X
    start                                             X
    stop                                              X
    pause_resume                                      X
    interrogate                                       X
    user_defined                                      X
    change_owner                                      X
    =======================  ====  ========  =======  =======

Only the registry and file object types have 'applies to' properties. These
should match what you see when you look at the properties for an object.

    **File types:**

        - this_folder_only: Applies only to this object
        - this_folder_subfolders_files (default): Applies to this object
          and all sub containers and objects
        - this_folder_subfolders: Applies to this object and all sub
          containers, no files
        - this_folder_files: Applies to this object and all file
          objects, no containers
        - subfolders_files: Applies to all containers and objects
          beneath this object
        - subfolders_only: Applies to all containers beneath this object
        - files_only: Applies to all file objects beneath this object

    .. note::

        'applies to' properties can only be modified on directories. Files
        will always be ``this_folder_only``.

    **Registry types:**

        - this_key_only: Applies only to this key
        - this_key_subkeys: Applies to this key and all subkeys
        - subkeys_only: Applies to all subkeys beneath this object

�N)�CommandExecutionError�SaltInvocationErrorFT�daclcCstjj��sdStsdStS)z4
    Only load if Win32 Libraries are installed
    )Fzwin_dacl: Requires Windows)Fzwin_dacl: Requires pywin32)�salt�utils�platformZ
is_windows�	HAS_WIN32�__virtualname__�r
r
�G/opt/saltstack/salt/lib/python3.10/site-packages/salt/utils/win_dacl.py�__virtual__�s
rcCs$tsdSGdd�d�}|r|�S|S)a_
    Helper function for instantiating a Flags object

    Args:

        instantiated (bool):
            True to return an instantiated object, False to return the object
            definition. Use False if inherited by another class. Default is
            True.

    Returns:
        object: An instance of the Flags object or its definition
    Nc@s�eZdZdZdddddddd	d
ddd
�idd�dd�dd�dd�dd�dd�dd�dd�dd�d d!�d"d#�d$d%�d&d'�d(d�d)d�d*d�d+d�dddddddddd d"d$d&d,�
�d-�d.ddd.d/ddd0d1d2d3�
idd4�dd5�dd6�dd7�dd8�dd9�d d!�d"d:�d$d;�d&d<�d=d�d>d�d?d�d@d�dAd�dBd�dCd �d"d$d&dD��d-�ddEddd	d
dF�id-�dGdHdIdJdKdLdM�dHdGd#d%d'dNdd"d$d&dO�
d-�d.dPdddQdRdSdTdU�iddV�ddW�ddX�ddY�ddZ�dd[�dd\�dd]�dd^�d"d_�d$d`�d&da�dbd�dcd�ddd�ded�dfd�ddddd"d$d&dg��d-�dh�Zdidjdkdldmdndodpdddqdrdsdtdu�dvdwdxdpddsdy�dvdwdxdpddsdy�dz�Zd{ejd|ejejd{ejd|iZ	ej
ejejd}�Z
ejejd~�Zejejejejejejd�Zd�S)�zflags.<locals>.FlagszV
        Object containing all the flags for dealing with Windows permissions
        zFull controlZModifyzRead & execute with writezRead & executeZReadZWrite�����)r
ri�rrr�full_control�modifyZread_execute�read�write�zList folder / read data�zCreate files / write data�zCreate folders / append data�zRead extended attributes�zWrite extended attributes� zTraverse folder / execute file�@zDelete subfolders and files�zRead attributes�zWrite attributesiZDelete�zRead permissions�zChange permissions�zTake ownershipZlist_folderZcreate_filesZcreate_foldersZtraverse_folder)
Zdelete_subfolders_filesZ	read_dataZ
write_dataZappend_dataZexecute_fileZread_eaZwrite_eaZread_attributesZwrite_attributes�delete�read_permissions�change_permissions�take_ownership)�basic�advancedzFull ControlZExecute�?��)
r(r)r*ii i@l��rrrzQuery Valuez	Set Valuez
Create SubkeyzEnumerate SubkeysZNotifyzCreate LinkzRead Controlz	Write DACzWrite OwnerZquery_valueZ	set_valueZ
create_subkeyZenum_subkeys�notifyZcreate_linkr")Zread_controlZ	write_dacZwrite_ownerZChange)r
rrrZchangerZPrintzManage this printerzManage documents���0)r,r-r.�print�manage_printerZmanage_documents�)
r1rrr r!r0r/r#r$r%zRead & Write����)r2r3r4r5rZ
read_writerrzQuery Configz
Change ConfigzQuery StatuszEnumerate DependentsZStartZStopzPause/ResumeZInterrogatezUser-Defined ControlzRead PermissionszChange PermissionszChange OwnerZquery_configZ
change_configZquery_statusZenum_dependents�start)�stopZpause_resumeZinterrogateZuser_definedr#r$Zchange_owner)�file�registry�share�printer�servicezThis folder onlyzThis folder and fileszThis folder and subfoldersz!This folder, subfolders and filesz
Files onlyzSubfolders onlyzSubfolders and files onlyr��	�
�)rrrr=r>r?r@Zthis_folder_onlyZthis_folder_filesZthis_folder_subfolders�this_folder_subfolders_filesZ
files_onlyZsubfolders_onlyZsubfolders_filesz
This key onlyzThis key and subkeyszSubkeys only)rrr?Z
this_key_only�this_key_subkeysZsubkeys_only�r8r9�
registry32�grant�deny)r�group�owner)�	protected�unprotected)r8r<r;r9rDr:N)�__name__�
__module__�__qualname__�__doc__�	ace_perms�ace_prop�
win32security�ACCESS_ALLOWED_ACE_TYPE�ACCESS_DENIED_ACE_TYPE�ace_type�DACL_SECURITY_INFORMATION�GROUP_SECURITY_INFORMATION�OWNER_SECURITY_INFORMATION�elementZ#PROTECTED_DACL_SECURITY_INFORMATIONZ%UNPROTECTED_DACL_SECURITY_INFORMATION�inheritanceZSE_FILE_OBJECTZ
SE_SERVICEZ
SE_PRINTERZSE_REGISTRY_KEYZSE_REGISTRY_WOW64_32KEYZ
SE_LMSHARE�obj_typer
r
r
r�Flags�s��
�������	�
���
��������6�
�������	�
���
��������(��
�
���
��������	���
���������7��	��&���
�r[)r)Zinstantiatedr[r
r
r�flags�s
zr\r8cs*tsdSG�fdd�dtd����||�S)aO
    Helper function for instantiating a Dacl class.

    Args:

        obj_name (str):
            The full path to the object. If None, a blank DACL will be created.
            Default is None.

        obj_type (str):
            The type of object. Default is 'File'

    Returns:
        object: An instantiated Dacl object
    NcsleZdZdZddd�Zdd�Zdd	�Z�fd
d�Zdd
�Zdd�Z	dd�Z
ddd�Zddd�Zddd�Z
dS)zdacl.<locals>.Daclz
        DACL Object
        Nr8c
Ss�|��|jvrtd|����|��|_|durt��|_dSd|jvr(|�|�}zt�||j|j|j	d�}Wn!t
jyY}zd|jvrTd|��}t
�|�t|���d}~ww|��|_|jdurkt��|_dSdS)a�
            Either load the DACL from the passed object or create an empty DACL.
            If `obj_name` is not passed, an empty DACL is created.

            Args:

                obj_name (str):
                    The full path to the object. If None, a blank DACL will be
                    created

                obj_type (Optional[str]):
                    The type of object.

            Returns:
                obj: A DACL object

            Usage:

            .. code-block:: python

                # Create an Empty DACL
                dacl = Dacl(obj_type=obj_type)

                # Load the DACL of the named object
                dacl = Dacl(obj_name, obj_type)
            �Invalid "obj_type" passed: Nr9rzThe system cannot findzSystem cannot find )�lowerrZr�	dacl_typerQZACLr�get_reg_name�GetNamedSecurityInforX�
pywintypes�error�strerror�log�	exceptionr�GetSecurityDescriptorDacl)�self�obj_namerZ�sd�exc�msgr
r
r�__init__�s.


�


��

�zdacl.<locals>.Dacl.__init__c
Ss�ddddddddddddd�}|�d�}|�d�}z||��}Wnty5t�d|�td	|����w|�d|�d
�|�S)aY
            Take the obj_name and convert the hive to a valid registry hive.

            Args:

                obj_name (str):
                    The full path to the registry key including the hive, eg:
                    ``HKLM\SOFTWARE\salt``. Valid options for the hive are:

                    - HKEY_LOCAL_MACHINE
                    - MACHINE
                    - HKLM
                    - HKEY_USERS
                    - USERS
                    - HKU
                    - HKEY_CURRENT_USER
                    - CURRENT_USER
                    - HKCU
                    - HKEY_CLASSES_ROOT
                    - CLASSES_ROOT
                    - HKCR

            Returns:
                str:
                    The full path to the registry key in the format expected by
                    the Windows API

            Usage:

            .. code-block:: python

                import salt.utils.win_dacl
                dacl = salt.utils.win_dacl.Dacl()
                valid_key = dacl.get_reg_name('HKLM\SOFTWARE\salt')

                # Returns: MACHINE\SOFTWARE\salt
            �MACHINE�USERS�CURRENT_USER�CLASSES_ROOT)�HKEY_LOCAL_MACHINErnZHKLMZ
HKEY_USERSroZHKU�HKEY_CURRENT_USERrpZHKCUZHKEY_CLASSES_ROOTrqZHKCR�\rzInvalid Registry Hive: %szInvalid Registry Hive: z\\)	�split�pop�upper�KeyErrorrerfr�insert�join)rhriZhivesZregZpassed_hiveZ
valid_hiver
r
rr`s.*�

�
zdacl.<locals>.Dacl.get_reg_namec
Ss�t|�}||j|jvrtd|j����|jdurtd��d}t|t�rLz|j|jd|}WnItyK}zd|��}t	�
|�t||��d}~ww|D]+}	z||j|jd|	O}WqNtyy}zd|	��}t	�
|�t||��d}~ww|��dvr�td	|����zE|��d
kr�|j�
tj|j�|ji��|�||�WdS|��dkr�|j�tj|j�|ji��|�||�WdSt	�
d|�td
|����ty�}z
dd|��fWYd}~Sd}~ww)a�
            Add an ACE to the DACL

            Args:

                principal (str):
                    The sid of the user/group to for the ACE

                access_mode (str):
                    Determines the type of ACE to add. Must be either ``grant``
                    or ``deny``.

                permissions (str, list):
                    The type of permissions to grant/deny the user. Can be one
                    of the basic permissions, or a list of advanced permissions.

                applies_to (str):
                    The objects to which these permissions will apply. Not all
                    these options apply to all object types.

            Returns:
                bool: True if successful, otherwise False

            Usage:

            .. code-block:: python

                dacl = Dacl(obj_type=obj_type)
                dacl.add_ace(sid, access_mode, permission, applies_to)
                dacl.save(obj_name, protected)
            zInvalid 'applies_to' for type Nz+You must load the DACL before adding an ACErr&zInvalid permission specified: r'�rErFzInvalid Access Mode: rErFzInvalid access mode: %szInvalid access mode: FzError: T)�get_sidrPr_rr�
isinstance�strrOrxrerfrr^�AddAccessAllowedAceExrQ�ACL_REVISION_DS�get�AddAccessDeniedAceEx�	Exception)
rh�	principal�access_mode�permissions�
applies_to�sidZ	perm_flagrkrl�permr
r
r�add_aceSsf 
�




��


��
������zdacl.<locals>.Dacl.add_acec	s|��}��}��}��}��}td|j���D]�}|j�|�}|ddtj@dkr�|ddtjkrF|j�tj|dd|d|d�q|ddtj	krb|j�tj|dd|d|d�q|ddtj
kr~|j�tj|dd|d|d�q|ddtjkr�|j�tj|dd|d|d�qtd|j���D]}|j�|�}|ddtj@tjk�r!|ddtjA}|ddtjkr�|j�tj||d|d�q�|ddtj	kr�|j�tj||d|d�q�|ddtj
k�r	|j�tj||d|d�q�|ddtjk�r!|j�tj||d|d�q�td|j���D]}|j�|�}|j�tj|dd|d|d��q*td|j���D]}|j�|�}|j�tj|ddtjA|d|d��qNtd|j���D]}|j�|�}|j�tj|dd|d|d��qutd|j���D]}|j�|�}|j�tj|ddtjA|d|d��q�|j|_dS)a\
            Put the ACEs in the ACL in the proper order. This is necessary
            because the add_ace function puts ACEs at the end of the list
            without regard for order. This will cause the following Windows
            Security dialog to appear when viewing the security for the object:

            ``The permissions on Directory are incorrectly ordered, which may
            cause some entries to be ineffective.``

            .. note:: Run this function after adding all your ACEs.

            Proper Orders is as follows:

                1. Implicit Deny
                2. Inherited Deny
                3. Implicit Deny Object
                4. Inherited Deny Object
                5. Implicit Allow
                6. Inherited Allow
                7. Implicit Allow Object
                8. Inherited Allow Object

            Usage:

            .. code-block:: python

                dacl = Dacl(obj_type=obj_type)
                dacl.add_ace(sid, access_mode, applies_to, permission)
                dacl.order_acl()
                dacl.save(obj_name, protected)
            rrrN)
�ranger�GetAceCount�GetAcerQ�
INHERITED_ACErSr�r�ZACCESS_DENIED_OBJECT_ACE_TYPErRrZACCESS_ALLOWED_OBJECT_ACE_TYPE)	rhZnew_daclZ	deny_daclZ
deny_obj_daclZ
allow_daclZallow_obj_dacl�i�acerP��Daclr
r�	order_acl�s� ���������������zdacl.<locals>.Dacl.order_aclcSsBt|�}|��}i}|D]}|||vr||||i||<q|S)a�
            Get the ACE for a specific principal.

            Args:

                principal (str):
                    The name of the user or group for which to get the ace. Can
                    also be a SID.

            Returns:
                dict: A dictionary containing the ACEs found for the principal

            Usage:

            .. code-block:: python

                dacl = Dacl(obj_type=obj_type)
                dacl.get_ace()
            )�get_name�	list_aces)rhr�Zaces�retrYr
r
r�get_ace.s�zdacl.<locals>.Dacl.get_acec	Ss~iid�}td|j���D]/}|j�|�}|�|�\}}}}}|||vr1||d�||||<q
|||d�i|||<q
|S)a
            List all Entries in the dacl.

            Returns:
                dict: A dictionary containing the ACEs for the object

            Usage:

            .. code-block:: python

                dacl = Dacl('C:\Temp')
                dacl.list_aces()
            ��	Inherited�
Not Inheritedr)�
applies tor�)r�rr�r��_ace_to_dict)	rhr�r�r��user�a_typeZa_propZa_permsrYr
r
rr�Ms
�
�zdacl.<locals>.Dacl.list_acescSsxt�|d�}t|�}|j|dd}|ddtj@dk}|ddtj@dk}d}|jdvrc|dd}|rB|ddtjA}|rM|ddtjA}z
|j|j|}Wntybd}Ynw|jd	krjd
n|j}|j	|d�
|dg�}	|	s�g}	|j	|dD]}
t|
t�r�q�|d|
@|
kr�|	�
|j	|d|
�q�|	��|	s�d
|d��g}	||||	|r�dfSdfS)zP
            Helper function for creating the ACE return dictionary
            rrrrrZNArCzUnknown propagationrDr9r&r'zUndefined Permission: r�r�)rQ�ConvertSidToStringSidr�rTr�ZNO_PROPAGATE_INHERIT_ACEr_rPrxrOr�r}r~�append�sort)rhr�r�r�rT�	inheritedZcontainer_onlyrPrZrOr�r
r
rr�psL
�
���zdacl.<locals>.Dacl._ace_to_dict�allc	Ss�t|�}|��}d}g}td|j���D]@}|j�||�}|ddtj@dk}|d|krT|sT|dks@|j|dd|krT|j�	||�|�
|�|��|d7}q|s]d|��g}|S)a�
            Remove a specific ACE from the DACL.

            Args:

                principal (str):
                    The user whose ACE to remove. Can be the user name or a SID.

                ace_type (str):
                    The type of ACE to remove. If not specified, all ACEs will
                    be removed. Default is 'all'. Valid options are:

                    - 'grant'
                    - 'deny'
                    - 'all'

            Returns:
                list: List of removed aces

            Usage:

            .. code-block:: python

                dacl = Dacl(obj_name='C:\temp', obj_type='file')
                dacl.rm_ace('Users')
                dacl.save(obj_name='C:\temp')
            rrrrr�zACE not found for )r|r^r�rr�r�rQr�rT�	DeleteAcer�r�)	rhr�rTr��offsetr�r�r�r�r
r
r�rm_ace�s �zdacl.<locals>.Dacl.rm_acecSs�d}g}|��}td|j���D]:}|j�||�}|ddtj@dk}|sJ|dks6|j|dd|krJ|j�||�|�	|�
|��|d7}q|S)ae
            Removes all ACEs from the DACL.

            Args:

                ace_type (str):
                    The type of ACE to remove. If not specified, all ACEs will
                    be removed. Default is 'all'. Valid options are:

                    - 'grant'
                    - 'deny'
                    - 'all'

            Returns:
                list: List of removed aces

            Usage:

            .. code-block:: python

                dacl = Dacl(obj_name='C:\temp', obj_type='file')
                dacl.rm_all_aces()
                dacl.save(obj_name='C:\temp')
            rrrr�)r^r�rr�r�rQr�rTr�r�r�)rhrTr�r�r�r�r�r
r
r�rm_all_aces�s�zdacl.<locals>.Dacl.rm_all_acesc
Ss�|jd}|dur|r||jdB}n||jdB}|jdvr$|�|�}zt�||j|j|dd|jd�WdStj	yM}z	t
d|��|j��d}~ww)ax
            Save the DACL

            Args:

                obj_name (str):
                    The object for which to set permissions. This can be the
                    path to a file or folder, a registry key, printer, etc. For
                    more information about how to format the name see:

                    https://msdn.microsoft.com/en-us/library/windows/desktop/aa379593(v=vs.85).aspx

                protected (Optional[bool]):
                    True will disable inheritance for the object. False will
                    enable inheritance. None will make no change. Default is
                    ``None``.

            Returns:
                bool: True if successful, Otherwise raises an exception

            Usage:

            .. code-block:: python

                dacl = Dacl(obj_type='file')
                dacl.save('C:\Temp', True)
            rNrIrJ�r9rDzFailed to set permissions: T)rXrYr_r`rQ�SetNamedSecurityInforZrrbrcrrd)rhrirIZsec_inforkr
r
r�saves0



�����zdacl.<locals>.Dacl.save�Nr8)r�)N)rKrLrMrNrmr`r�r�r�r�r�r�r�r�r
r�r
rr��s
6G`{#
E
2,r�F)rr\�rirZr
r�rr�s
~cCs�|durd}z	tjj�|�}Wnty|}Ynwzt�|�}W|Stjy8t	�
d|�td|����ty@t�w)a�
    Converts a username to a sid, or verifies a sid. Required for working with
    the DACL.

    Args:

        principal(str):
            The principal to lookup the sid. Can be a sid or a username.

    Returns:
        PySID Object: A sid

    Usage:

    .. code-block:: python

        # Get a user's sid
        salt.utils.win_dacl.get_sid('jsnuffy')

        # Verify that the sid is valid
        salt.utils.win_dacl.get_sid('S-1-5-32-544')
    N�NULL SIDzInvalid user/group or sid: %szInvalid user/group or sid: )rrZ
win_functionsZget_sid_from_namerrQ�ConvertStringSidToSidrbrcrerf�	TypeError)r�r�r
r
rr|Ns ���r|cCsl|durd}zt�|�WStyt|�}Ynwzt�|�WStjy5t�d|�td|����w)a�
    Converts a PySID object to a string SID.

    Args:

        principal(str):
            The principal to lookup the sid. Must be a PySID object.

    Returns:
        str: A string sid

    Usage:

    .. code-block:: python

        # Get a PySID object
        py_sid = salt.utils.win_dacl.get_sid('jsnuffy')

        # Get the string version of the SID
        salt.utils.win_dacl.get_sid_string(py_sid)
    Nr�zInvalid principal %szInvalid principal )	rQr�r�r|rbrcrerfr�r�r
r
r�get_sid_string{s��r�cCs0t|tj�r	|}n/|durd}zt�|�}Wn!tjy7z
t�d|�d}Wntjy4|}YnwYnwt|�}zt�d|�d}|�	d�rOd|��}|WStjy�}z9|j
dkr|�	d�rqt�d|�WYd}~dSt�d	|�|WYd}~Sd
|�d|j
�d�}t�|�t||��d}~ww)
a�
    Gets the name from the specified principal.

    Args:

        principal (str):
            Find the Normalized name based on this. Can be a PySID object, a SID
            string, or a username in any capitalization.

            .. note::
                Searching based on the username can be slow on hosts connected
                to large Active Directory domains.

    Returns:
        str: The username that corresponds to the passed principal. If there is
             no corresponding username, the string SID will be returned.
             Capability SIDs will return ``None``.


    Usage:

    .. code-block:: python

        salt.utils.win_dacl.get_name('S-1-5-32-544')
        salt.utils.win_dacl.get_name('adminisTrators')
    N�S-1-0-0rzS-1-5-80zNT Service\i4zS-1-15-3z1Name mapping not available for capability SID: %sz�Could not resolve SID: %s
The user has either been removed from the system or is a domain user and the system is not connected to the domainzError resolving "z: �")r}rbZSIDTyperQr�rcZLookupAccountNamer�ZLookupAccountSid�
startswith�winerrorre�debugrdrfr)r�Zsid_objZstr_sid�namerk�messager
r
rr��sF���


	
�

��r�c
Cs�z
t�j|��}Wntytd|����w|dvr#t��|�}zt�||tj	�}|�
�}Wt|�StyBd}Yt|�Stj
ys}z%|jdksT|jdkrWd}nt�d|�td|��|j��WYd}~t|�Sd}~ww)	a�
    Gets the owner of the passed object

    Args:

        obj_name (str):
            The path for which to obtain owner information. The format of this
            parameter is different depending on the ``obj_type``

        obj_type (str):
            The type of object to query. This value changes the format of the
            ``obj_name`` parameter as follows:

            - file: indicates a file or directory
                - a relative path, such as ``FileName.txt`` or ``..\FileName``
                - an absolute path, such as ``C:\DirName\FileName.txt``
                - A UNC name, such as ``\\ServerName\ShareName\FileName.txt``
            - service: indicates the name of a Windows service
            - printer: indicates the name of a printer
            - registry: indicates a registry key
                - Uses the following literal strings to denote the hive:
                    - HKEY_LOCAL_MACHINE
                    - MACHINE
                    - HKLM
                    - HKEY_USERS
                    - USERS
                    - HKU
                    - HKEY_CURRENT_USER
                    - CURRENT_USER
                    - HKCU
                    - HKEY_CLASSES_ROOT
                    - CLASSES_ROOT
                    - HKCR
                - Should be in the format of ``HIVE\Path\To\Key``. For example,
                    ``HKLM\SOFTWARE\Windows``
            - registry32: indicates a registry key under WOW64. Formatting is
                the same as it is for ``registry``
            - share: indicates a network share

    Returns:
        str: The owner (group or user)

    Usage:

    .. code-block:: python

        salt.utils.win_dacl.get_owner('c:\\file')
    r]r�r�r�2zFailed to get the owner: %szFailed to get owner: N)r\rZr^rxrrr`rQrarW�GetSecurityDescriptorOwner�MemoryErrorrbrcr�rerfrrdr�)rirZ�
obj_type_flag�security_descriptorZ	owner_sidrkr
r
r�	get_owners66��
���
���r�c
Cs�z
t�j|��}Wntytd|����wd|��vr+t��|�}t�d|�zt	�
||t	j�}|��}Wn9t
yDd}Yn/tjyr}z"|jdksV|jdkrYd}nt�d|�td|��|j��WYd	}~nd	}~wwtt	�|��S)
a�
    Gets the primary group of the passed object

    Args:

        obj_name (str):
            The path for which to obtain primary group information

        obj_type (str):
            The type of object to query. This value changes the format of the
            ``obj_name`` parameter as follows:

            - file: indicates a file or directory
                - a relative path, such as ``FileName.txt`` or ``..\FileName``
                - an absolute path, such as ``C:\DirName\FileName.txt``
                - A UNC name, such as ``\\ServerName\ShareName\FileName.txt``
            - service: indicates the name of a Windows service
            - printer: indicates the name of a printer
            - registry: indicates a registry key
                - Uses the following literal strings to denote the hive:
                    - HKEY_LOCAL_MACHINE
                    - MACHINE
                    - HKLM
                    - HKEY_USERS
                    - USERS
                    - HKU
                    - HKEY_CURRENT_USER
                    - CURRENT_USER
                    - HKCU
                    - HKEY_CLASSES_ROOT
                    - CLASSES_ROOT
                    - HKCR
                - Should be in the format of ``HIVE\Path\To\Key``. For example,
                    ``HKLM\SOFTWARE\Windows``
            - registry32: indicates a registry key under WOW64. Formatting is
                the same as it is for ``registry``
            - share: indicates a network share

    Returns:
        str: The primary group for the object

    Usage:

    .. code-block:: python

        salt.utils.win_dacl.get_primary_group('c:\\file')
    r]r9zName converted to: %sr�rr�z#Failed to get the primary group: %szFailed to get primary group: N)r\rZr^rxrrr`rer�rQrarV�GetSecurityDescriptorGroupr�rbrcr�rfrrdr�r�)rirZr�r�Zprimary_group_gidrkr
r
r�get_primary_groupWs46������
r�c

Cst|�}t�}|��|jvrtd|����d|��vr!t��|�}t�}t�	dd�}|�
|tjf�t�	dd�}|�
|tjf�t
��}t�|tjtjB�}t�|d|�zt�||j|��|jd|ddd�WdStjy�}	zt�d	||	�td
|��|	j��d}	~	ww)ae
    Set the owner of an object. This can be a file, folder, registry key,
    printer, service, etc...

    Args:

        obj_name (str):
            The object for which to set owner. This can be the path to a file or
            folder, a registry key, printer, etc. For more information about how
            to format the name see:

            https://msdn.microsoft.com/en-us/library/windows/desktop/aa379593(v=vs.85).aspx

        principal (str):
            The name of the user or group to make owner of the object. Can also
            pass a SID.

        obj_type (Optional[str]):
            The type of object for which to set the owner. Default is ``file``

    Returns:
        bool: True if successful, raises an error otherwise

    Usage:

    .. code-block:: python

        salt.utils.win_dacl.set_owner('C:\MyDirectory', 'jsnuffy', 'file')
    r]r9��SeTakeOwnershipPrivilege�SeRestorePrivilegerrHNzFailed to make %s the owner: %szFailed to set owner: T�r|r\r^rZrrr`�setrQ�LookupPrivilegeValue�add�win32con�SE_PRIVILEGE_ENABLED�win32api�GetCurrentProcess�OpenProcessToken�TOKEN_ALL_ACCESS�TOKEN_ADJUST_PRIVILEGES�AdjustTokenPrivilegesr�rXrbrcrerfrrd)
rir�rZr��	obj_flags�	new_privs�luid�p_handle�t_handlerkr
r
r�	set_owner�s@��
���r�c

Cs|durd}t|�}t�}|��|jvrtd|����d|��vr't��|�}t�}t�	dd�}|�
|tjf�t�	dd�}|�
|tjf�t
��}t�|tjtjB�}t�|d|�zt�||j|��|jd	d|dd�WdStjy�}	zt�d
||	�td|��|	j��d}	~	ww)
as
    Set the primary group of an object. This can be a file, folder, registry
    key, printer, service, etc...

    Args:

        obj_name (str):
            The object for which to set primary group. This can be the path to a
            file or folder, a registry key, printer, etc. For more information
            about how to format the name see:

            https://msdn.microsoft.com/en-us/library/windows/desktop/aa379593(v=vs.85).aspx

        principal (str):
            The name of the group to make primary for the object. Can also pass
            a SID.

        obj_type (Optional[str]):
            The type of object for which to set the primary group.

    Returns:
        bool: True if successful, raises an error otherwise

    Usage:

    .. code-block:: python

        salt.utils.win_dacl.set_primary_group('C:\MyDirectory', 'Administrators', 'file')
    N�Noner]r9r�r�r�rrGz'Failed to make %s the primary group: %szFailed to set primary group: Tr�)
rir�rZ�gidr�r�r�r�r�rkr
r
r�set_primary_group�sH ������r�rEc	Csx|durd|��vr
d}n|��dkrd}|rt|d�}nt||�}|�||�|�||||�|��|�||�dS)aO
    Set the permissions of an object. This can be a file, folder, registry key,
    printer, service, etc...

    Args:

        obj_name (str):
            The object for which to set permissions. This can be the path to a
            file or folder, a registry key, printer, etc. For more information
            about how to format the name see:

            https://msdn.microsoft.com/en-us/library/windows/desktop/aa379593(v=vs.85).aspx

        principal (str):
            The name of the user or group for which to set permissions. Can also
            pass a SID.

        permissions (str, list):
            The type of permissions to grant/deny the user. Can be one of the
            basic permissions, or a list of advanced permissions.

        access_mode (Optional[str]):
            Whether to grant or deny user the access. Valid options are:

            - grant (default): Grants the user access
            - deny: Denies the user access

        applies_to (Optional[str]):
            The objects to which these permissions will apply. Not all these
            options apply to all object types. Defaults to
            'this_folder_subfolders_files'

        obj_type (Optional[str]):
            The type of object for which to set permissions. Default is 'file'

        reset_perms (Optional[bool]):
            True will overwrite the permissions on the specified object. False
            will append the permissions. Default is False

        protected (Optional[bool]):
            True will disable inheritance for the object. False will enable
            inheritance. None will make no change. Default is None.

    Returns:
        bool: True if successful, raises an error otherwise

    Usage:

    .. code-block:: python

        salt.utils.win_dacl.set_permissions(
            'C:\Temp', 'jsnuffy', 'full_control', 'grant')
    Nr9rBr8rA�rZT)r^rr�r�r�r�)	rir�r�r�r�rZZreset_permsrI�obj_daclr
r
r�set_permissionsPs@
r�r�cCs$t||�}|�||�|�|�dS)a�
    Remove a user's ACE from an object. This can be a file, folder, registry
    key, printer, service, etc...

    Args:

        obj_name (str):
            The object from which to remove the ace. This can be the
            path to a file or folder, a registry key, printer, etc. For more
            information about how to format the name see:

            https://msdn.microsoft.com/en-us/library/windows/desktop/aa379593(v=vs.85).aspx

        principal (str):
            The name of the user or group for which to set permissions. Can also
            pass a SID.

        ace_type (Optional[str]):
            The type of ace to remove. There are two types of ACEs, 'grant' and
            'deny'. 'all' will remove all ACEs for the user. Default is 'all'

        obj_type (Optional[str]):
            The type of object for which to set permissions. Default is 'file'

    Returns:
        bool: True if successful, raises an error otherwise

    Usage:

    .. code-block:: python

        # Remove jsnuffy's grant ACE from C:\Temp
        salt.utils.win_dacl.rm_permissions('C:\\Temp', 'jsnuffy', 'grant')

        # Remove all ACEs for jsnuffy from C:\Temp
        salt.utils.win_dacl.rm_permissions('C:\\Temp', 'jsnuffy')
    T)rr�r�)rir�rTrZr�r
r
r�rm_permissions�s
&
r�cCs&t||d�}|dur|��S|�|�S)av
    Get the permissions for the passed object

    Args:

        obj_name (str):
            The name of or path to the object.

        principal (Optional[str]):
            The name of the user or group for which to get permissions. Can also
            pass a SID. If None, all ACEs defined on the object will be
            returned. Default is None

        obj_type (Optional[str]):
            The type of object for which to get permissions.

    Returns:
        dict: A dictionary representing the object permissions

    Usage:

    .. code-block:: python

        salt.utils.win_dacl.get_permissions('C:\Temp')
    r�N)rr�r�)rir�rZr�r
r
r�get_permissions�s
r�cCs�|��dvr
td|����|��}t||�}|��}t|�}|j|d�|��|j|d�|��d��}|s?td|����d}	td|j���D]}
|j�|
�}|d	|krf|j	|dd|krf|d
}	qI|	skdS|rq|	|kS|	|@|kS)a�
    Check if the object has a specific permission

    Args:

        obj_name (str):
            The name of or path to the object.

        principal (str):
            The name of the user or group for which to get permissions. Can also
            pass a SID.

        permission (str):
            The permission to verify. Valid options depend on the obj_type.

        access_mode (Optional[str]):
            The access mode to check. Is the user granted or denied the
            permission. Default is 'grant'. Valid options are:

            - grant
            - deny

        obj_type (Optional[str]):
            The type of object for which to check permissions. Default is 'file'

        exact (Optional[bool]):
            True for an exact match, otherwise check to see if the permission is
            included in the ACE. Default is True

    Returns:
        bool: True if the object has the permission, otherwise False

    Usage:

    .. code-block:: python

        # Does Joe have read permissions to C:\Temp
        salt.utils.win_dacl.has_permission('C:\\Temp', 'joe', 'read', 'grant', exact=False)

        # Does Joe have Full Control of C:\Temp
        salt.utils.win_dacl.has_permission('C:\\Temp', 'joe', 'full_control', 'grant')
    r{�Invalid "access_mode" passed: r&r'F�Invalid "permission" passed: Nrrr)
r^rrr|rOr�r�r�r�rT)rir��
permissionr�rZ�exactr�r��chk_flag�cur_flagr�r�r
r
r�has_permission�s..
�"�r�c
	Cst|t�rt||||||d�S|��dvrtd|����|��}t||�}|��}t|�}d}|D]%}	||j|d�|	��|j|d�|	��d��O}|sVtd|	����q1d	}
t	d|j�
��D]}|j�|�}|d
|kr~|j|dd|kr~|d}
qa|
s�dS|r�|
|kS|
|@|kS)a|
    Check if the object has the passed permissions. Can be all them or the exact
    permissions passed and nothing more.

    Args:

        obj_name (str):
            The name of or path to the object.

        principal (str):
            The name of the user or group for which to get permissions. Can also
            pass a SID.

        permissions (list):
            The list of permissions to verify

        access_mode (Optional[str]):
            The access mode to check. Is the user granted or denied the
            permission. Default is 'grant'. Valid options are:

            - grant
            - deny

        obj_type (Optional[str]):
            The type of object for which to check permissions. Default is 'file'

        exact (Optional[bool]):
            ``True`` checks if the permissions are exactly those passed in
            permissions. ``False`` checks to see if the permissions are included
            in the ACE. Default is ``True``

    Returns:
        bool: True if the object has the permission, otherwise False

    Usage:

    .. code-block:: python

        # Does Joe have read and write permissions to C:\Temp
        salt.utils.win_dacl.has_permission('C:\\Temp', 'joe', ['read', 'write'], 'grant', exact=False)

        # Does Joe have Full Control of C:\Temp
        salt.utils.win_dacl.has_permissions('C:\\Temp', 'joe', 'full_control', 'grant')
    )rirZr�r�r�r�r{r�rr&r'Fr�Nrr)
r}r~r�r^rrr|rOr�r�r�r�rT)
rir�r�r�rZr�r�r�r�r�r�r�r�r
r
r�has_permissionsLsF
0�

��"�r�cCs>|dvrtd|����|rt|d�}nt||�}|�||�S)a�
    Enable or disable an objects inheritance.

    Args:

        obj_name (str):
            The name of the object

        enabled (bool):
            True to enable inheritance, False to disable

        obj_type (Optional[str]):
            The type of object. Only three objects allow inheritance. Valid
            objects are:

            - file (default): This is a file or directory
            - registry
            - registry32 (for WOW64)

        clear (Optional[bool]):
            True to clear existing ACEs, False to keep existing ACEs.
            Default is False

    Returns:
        bool: True if successful, otherwise an Error

    Usage:

    .. code-block:: python

        salt.utils.win_dacl.set_inheritance('C:\Temp', False)
    rCz*obj_type called with incorrect parameter: r�)rrr�)ri�enabledrZ�clearr�r
r
r�set_inheritance�s!�
r�cCsRt||d�}tj}td|j���D]}|j�|�}|dd|@|kr&dSqdS)a�
    Get an object's inheritance.

    Args:

        obj_name (str):
            The name of the object

        obj_type (Optional[str]):
            The type of object. Only three object types allow inheritance. Valid
            objects are:

            - file (default): This is a file or directory
            - registry
            - registry32 (for WOW64)

            The following should return False as there is no inheritance:

            - service
            - printer
            - share

    Returns:
        bool: True if enabled, otherwise False

    Usage:

    .. code-block:: python

        salt.utils.win_dacl.get_inheritance('HKLM\SOFTWARE\salt', 'registry')
    r�rrTF)rrQr�r�r�r�)rirZr�r�r�r�r
r
r�get_inheritance�s �r�c
Cs�t|d�}d|��vr!|�|�}t�d|�|�|�}t�d|�z
t�j|��}Wnty9td|����wd}	|rC|	t	j
O}	|rJ|	t	jO}	|rQ|	t	jO}	|rX|	t	j
O}	|	s^td��t�}
t	�dd	�}|
�|tjf�t	�dd
�}|
�|tjf�t	�dd�}|
�|tjf�t��}t	�|t	jtjB�}
t	�|
d|
�t	�|||	�}|��}|��}|��}|��}zt	�|||	||||�WdStj y�}zt!d|j"����d
}~ww)a�
    Copy the security descriptor of the Source to the Target. You can specify a
    specific portion of the security descriptor to copy using one of the
    `copy_*` parameters.

    .. note::
        At least one `copy_*` parameter must be ``True``

    .. note::
        The user account running this command must have the following
        privileges:

        - SeTakeOwnershipPrivilege
        - SeRestorePrivilege
        - SeSecurityPrivilege

    Args:

        source (str):
            The full path to the source. This is where the security info will be
            copied from

        target (str):
            The full path to the target. This is where the security info will be
            applied

        obj_type (str): file
            The type of object to query. This value changes the format of the
            ``obj_name`` parameter as follows:
            - file: indicates a file or directory
                - a relative path, such as ``FileName.txt`` or ``..\FileName``
                - an absolute path, such as ``C:\DirName\FileName.txt``
                - A UNC name, such as ``\\ServerName\ShareName\FileName.txt``
            - service: indicates the name of a Windows service
            - printer: indicates the name of a printer
            - registry: indicates a registry key
                - Uses the following literal strings to denote the hive:
                    - HKEY_LOCAL_MACHINE
                    - MACHINE
                    - HKLM
                    - HKEY_USERS
                    - USERS
                    - HKU
                    - HKEY_CURRENT_USER
                    - CURRENT_USER
                    - HKCU
                    - HKEY_CLASSES_ROOT
                    - CLASSES_ROOT
                    - HKCR
                - Should be in the format of ``HIVE\Path\To\Key``. For example,
                    ``HKLM\SOFTWARE\Windows``
            - registry32: indicates a registry key under WOW64. Formatting is
                the same as it is for ``registry``
            - share: indicates a network share

        copy_owner (bool): True
            ``True`` copies owner information. Default is ``True``

        copy_group (bool): True
            ``True`` copies group information. Default is ``True``

        copy_dacl (bool): True
            ``True`` copies the DACL. Default is ``True``

        copy_sacl (bool): True
            ``True`` copies the SACL. Default is ``True``

    Returns:
        bool: ``True`` if successful

    Raises:
        SaltInvocationError: When parameters are invalid
        CommandExecutionError: On failure to set security

    Usage:

    .. code-block:: python

        salt.utils.win_dacl.copy_security(
            source='C:\\temp\\source_file.txt',
            target='C:\\temp\\target_file.txt',
            obj_type='file')

        salt.utils.win_dacl.copy_security(
            source='HKLM\\SOFTWARE\\salt\\test_source',
            target='HKLM\\SOFTWARE\\salt\\test_target',
            obj_type='registry',
            copy_owner=False)
    r�r9zSource converted to: %szTarget converted to: %sr]rzCOne of copy_owner, copy_group, copy_dacl, or copy_sacl must be Truer�r�r�ZSeSecurityPrivilegezFailed to set security info: NT)#rr^r`re�infor\rZrxrrQrWrVrUZSACL_SECURITY_INFORMATIONr�r�r�r�r�r�r�r�r�r�r�rar�r�rgZGetSecurityDescriptorSaclr�rbrcrrd)�source�targetrZZ
copy_ownerZ
copy_groupZ	copy_daclZ	copy_saclr�r�Zsecurity_flagsr�r�r�r�ZsecZsd_sidZsd_gidZsd_daclZsd_saclrkr
r
r�
copy_security	sd
b

�



������r�cCs�|��}|�d�}t||d�}i}|D]�}	t|	d�}
|
t|	d�kr/|d�d�|��|	��q|
durA|d�d�|��|	��q|
|dvrh|�|	i�||	d	||	d
<d||	vrg||	d||	d<qt||
||	d	||dd
�s�|�|	i�||	d	||	d
<d||	vr�||	d}t	�j
||}t	�j
||}
||d|
vr�|d|
|d|
ks�|�|	i�|||	d<q|�rG|d�|i�|D]v}	t|	d�}
|dur�|d|�|	i�||	|d||	<q�|�sFz+t||
||	d
|||	�d�|d�|d�|i��|	i�||	|d||	<Wq�t
�yE}zd|d<|d�d�||	||	|j��WYd}~q�d}~wwq�|S)a�
    Helper function used by ``check_perms`` for checking and setting Grant and
    Deny permissions.

    Args:

        obj_name (str):
            The name or full path to the object

        obj_type (Optional[str]):
            The type of object for which to check permissions. Default is 'file'

        new_perms (dict):
            A dictionary containing the user/group and the basic permissions to
            check/grant, ie: ``{'user': {'perms': 'basic_permission'}}``.

        access_mode (str):
            The access mode to set. Either ``grant`` or ``deny``

        ret (dict):
            A dictionary to append changes to and return. If not passed, will
            create a new dictionary to return.

        test_mode (bool):
            ``True`` will only return the changes that would be made. ``False``
            will make the changes as well as return the changes that would be
            made.

    Returns:
        dict: A dictionary of return data as expected by the state system
    Z_permsr�r��commentz9{} Perms: Could not find a corresponding username for: {}Nz%{} Perms: Skipping Capability SID: {}r��permsr�r�T)rir�r�r�rZr�r��changes)rir�r�r�r�rZF�resultz8Failed to change {} permissions for "{}" to {}
Error: {})r^r�r�r�r��format�
capitalize�
setdefaultr�r\rPr�r�rrd)rirZ�	new_permsr�r��	test_modeZperms_label�	cur_permsr�r��	user_namer��at_flagZapplies_to_textrkr
r
r�_check_perms�s� 

�����
����

������r�c	
	Cs$|��t�jvrtd|����|��}|s|igdd�}d}	n|d}	g|d<|rqt|d�}t||d�}
||
krq|durC||dd	<n.zt|||d
�t�d|�||dd	<Wnt	ypd|d
<|d�
d|�d��Ynw|dur�|t||d�ks�|dur�||dd<n2zt|||d�t�d|r�dnd�||dd<Wnt	y�d|d
<|d�
d�
||��Ynw|�rct�d|�t||d�}|dD]�}|dd�|p�iD�v�rd|d|v�r|d�di�|du�r|dd�||d|i�nt||d|d�|dd�||d|i�|dd�|�p iD�v�rbd|d|v�rb|d�di�|du�rK|dd�||d|i�q�t||d|d�|dd�||d|i�q�t�d |�|du�rxt|||d||d!�}|du�r�t|||d||d!�}|�r�|�s�t�d|�t||d�}|dD]?}|d"d�|�p�iD�v�r�d|d|v�r�t||d|d�|d#d�|�p�iD�v�r�d|d|v�r�t||d|d��q�t|	t��r�|	�r�|d�d$|	�n|	�r�|	�|d�|d<d%�|d�|d<|�r|d�rd|d
<|S)&a�
    Check owner and permissions for the passed directory. This function checks
    the permissions and sets them, returning the changes made.

    .. versionadded:: 2019.2.0

    Args:

        obj_name (str):
            The name or full path to the object

        obj_type (Optional[str]):
            The type of object for which to check permissions. Default is 'file'

        ret (dict):
            A dictionary to append changes to and return. If not passed, will
            create a new dictionary to return.

        owner (str):
            The owner to set for the directory.

        grant_perms (dict):
            A dictionary containing the user/group and the basic permissions to
            check/grant, ie: ``{'user': {'perms': 'basic_permission'}}``.
            Default is ``None``.

        deny_perms (dict):
            A dictionary containing the user/group and permissions to
            check/deny. Default is ``None``.

        inheritance (bool):
            ``True`` will enable inheritance from the parent object. ``False``
            will disable inheritance. Default is ``True``.

        reset (bool):
            ``True`` will clear the DACL and set only the permissions defined
             in ``grant_perms`` and ``deny_perms``. ``False`` append permissions
             to the existing DACL. Default is ``False``. This does NOT affect
            inherited permissions.

        test_mode (bool):
            ``True`` will only return the changes that would be made. ``False``
            will make the changes as well as return the changes that would be
            made.

    Returns:
        dict: A dictionary of changes that have been made

    Usage:

    .. code-block:: bash

        # You have to use __utils__ in order for __opts__ to be available

        # To see changes to ``C:\Temp`` if the 'Users' group is given 'read & execute' permissions.
        __utils__['dacl.check_perms'](obj_name='C:\Temp',
                                      obj_type='file',
                                      owner='Administrators',
                                      grant_perms={
                                          'Users': {
                                              'perms': 'read_execute'
                                          }
                                      })

        # Specify advanced attributes with a list
        __utils__['dacl.check_perms'](obj_name='C:\Temp',
                                      obj_type='file',
                                      owner='Administrators',
                                      grant_perms={
                                          'jsnuffy': {
                                              'perms': [
                                                  'read_attributes',
                                                  'read_ea'
                                              ],
                                              'applies_to': 'files_only'
                                          }
                                      })
    r]T)r�r�r�r�r�r�r�r�r�rH)rir�rZzOwner set to %sFr�zFailed to change owner to "r�NrY)rir�rZz%s inheritanceZEnablingZ	Disablingz(Failed to set inheritance for "{}" to {}zResetting permissions for %sr�cS�h|]}t|��qSr
�r���.0�kr
r
r�	<setcomp>�	�zcheck_perms.<locals>.<setcomp>rEZremove_perms)rir�rTrZcSr�r
r�r�r
r
rr�	rrFz"Getting current permissions for %s)rirZr�r�r�r�cSr�r
r�r�r
r
rr
rcSr�r
r�r�r
r
rr
rr�
)r^r\rZrr�r�r�rer�rr�r�r�r�r�r��updater�r�r}r~ry�extendrz)
rirZr�rH�grant_perms�
deny_permsrY�resetr�Zorig_commentZ
current_ownerr�r�r
r
r�check_perms-	sZ
������

���
����
�

�
����rcCs|��}i}|D]�}t|�}|t|�krqd}|dvrwd||vrq||dvrad|d|vrat�j|D]+}	t�j||	|d|ddkr`|	}
t�j|D]}t�j|||
kr_|}qQq5|sp|dkrjd}n
d|vrpd	}n||d}|j||||d
|d�r�||||<q|S)NrCr�r�rFr�r8rAr9rBr�)r�r�r�r�)r^r�r�r\rPr�)r�rZr�r�r�r�r�r�r��flagr�Zflag1r
r
r�
_set_perms*
sL����
��r
c	Cs�i}|rt|d�}iid�}nt||d�}t||d�}|dur*t||||dd�|d<|dur9t||||dd�|d<|��|�||�rF|SiS)a�

    Set permissions for the given path

    .. versionadded:: 2019.2.0

    Args:

        obj_name (str):
            The name or full path to the object

        obj_type (Optional[str]):
            The type of object for which to check permissions. Default is 'file'

        grant_perms (dict):
            A dictionary containing the user/group and the basic permissions to
            grant, ie: ``{'user': {'perms': 'basic_permission'}}``. You can also
            set the ``applies_to`` setting here. The default for ``applise_to``
            is ``this_folder_subfolders_files``. Specify another ``applies_to``
            setting like this:

            .. code-block:: yaml

                {'user': {'perms': 'full_control', 'applies_to': 'this_folder'}}

            To set advanced permissions use a list for the ``perms`` parameter,
            ie:

            .. code-block:: yaml

                {'user': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder'}}

            To see a list of available attributes and applies to settings see
            the documentation for salt.utils.win_dacl.

            A value of ``None`` will make no changes to the ``grant`` portion of
            the DACL. Default is ``None``.

        deny_perms (dict):
            A dictionary containing the user/group and permissions to deny along
            with the ``applies_to`` setting. Use the same format used for the
            ``grant_perms`` parameter. Remember, deny permissions supersede
            grant permissions.

            A value of ``None`` will make no changes to the ``deny`` portion of
            the DACL. Default is ``None``.

        inheritance (bool):
            If ``True`` the object will inherit permissions from the parent, if
            ``False``, inheritance will be disabled. Inheritance setting will
            not apply to parent directories if they must be created. Default is
            ``False``.

        reset (bool):
            If ``True`` the existing DCL will be cleared and replaced with the
            settings defined in this function. If ``False``, new entries will be
            appended to the existing DACL. Default is ``False``.

    Returns:
        bool: True if successful

    Raises:
        CommandExecutionError: If unsuccessful

    Usage:

    .. code-block:: bash

        import salt.utils.win_dacl

        # To grant the 'Users' group 'read & execute' permissions.
        salt.utils.win_dacl.set_perms(obj_name='C:\Temp',
                                      obj_type='file',
                                      grant_perms={
                                          'Users': {
                                              'perms': 'read_execute'
                                          }
                                      })

        # Specify advanced attributes with a list
        salt.utils.win_dacl.set_perms(obj_name='C:\Temp',
                                      obj_type='file',
                                      grant_perms={
                                          'jsnuffy': {
                                              'perms': [
                                                  'read_attributes',
                                                  'read_ea'
                                              ],
                                              'applies_to': 'this_folder_only'
                                          }
                                      }"
    r�r�r�NrF)r�rZr�r�r�rE)rr�r
r�r�)	rirZrrrYrr�r�r�r
r
r�	set_perms^
s4c

�	
�	r)Tr�)r8)rENr8FN)r�r8)rEr8T)r8F)r8TTTT)F)r8NNNNTFF)r8NNTF)(rN�loggingZsalt.utils.platformrZsalt.utils.win_functionsZsalt.exceptionsrrrrbr�r�rQ�ImportError�	getLoggerrKrer	rr\rr|r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rr
rr
r
r
r�<module>s�
�



-'
`
U
V
NY
�
W
.#
�V
�
d
..
�
(
�~6�