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/modules/__pycache__/win_lgpo.cpython-310.pyc
o

�N�g���@s�dZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
mmZddlZddlZddlZddlZddlZddlmZmZddlmZddlmZmZmZmZm Z e�!e"�Z#dZ$ddiZ%e�&�j'Z(iid	�Z)d
Z*dZ+dZ,dZ-dZ.dZ/dZ0dZ1dZ2dZ3dZ4dZ5dZ6dZ7dZ8dZ9dZ:dZ;dZ<dZ=dZ>dZ?z�ddl@Z@ddlAZAddlBZBddlCZCddlAmDZDddlEmFZFd
Z*eD�Gd�Z+eD�Gd�Z,eD�Gd�Z-eD�Gd�Z.eD�Gd�Z/eD�Gd�Z0eD�Gd�Z1eD�Gd�Z2eD�Gd�Z3eD�Gd�Z4eD�Gd�Z5eD�Gd�Z6eD�Gd�Z7eD�Gd�Z8eD�Gd�Z9eD�Gd�Z:eD�Gd�Z;eD�Gd�Z<eD�Gd �Z=eD�Gd!�Z>eD�Gd"�Z?ejHjIZHejJ�KeH�L�d#��Md$d%�ZNWneO�yRd
Z*YnwGd&d'�d'�ZPd(d)�ZQd*d+�ZRd,d-�ZSd.d/�ZTd0d1�ZUd2d3�ZVd4d5�ZWd�d8d9�ZXd�d:d;�ZYd<d=�ZZd�d>d?�Z[d@dA�Z\d�dBdC�Z]dDdE�Z^d�dFdG�Z_dHdI�Z`dJdK�ZadLdM�ZbdNdO�ZcdPdQ�ZddRdS�Zed�dTdU�ZfdVdW�ZgdXdY�ZhdZd[�Zid\d]�Zjd^d_�Zkd`da�Zldbdc�Zmddde�Zndfdg�Zodhdi�Zpd�djdk�Zq	
d�dldm�Zr	
	
d�dndo�Zsdpdq�Zt	
d�drds�Zu	
	d�dtdu�Zv	7	
	
	
d�dvdw�Zwdxdy�Zxdzd{�Zyd|d}�Zzd~d�Z{d�d�d��Z|	�d�d�d��Z}d�d��Z~d�d�d��Zd�d�d��Z�d�d�d��Z�		
	
	7	
d�d�d��ZKd�d��Z�	7	
	
d�d�d��Z�	7	
	
	
d�d�d��Z�	7d�d�d��Z�d�d�d��Z�			
	7d�d�d�Z�dS)�a
Manage Local Policy on Windows

This module allows configuring local group policy (i.e. ``gpedit.msc``) on a
Windows machine.

.. versionadded:: 2016.11.0

.. warning::
    Local Group Policy will always be superseded by Domain Group policy. If
    policies are configured with Local Group Policy that are also configured
    with Domain Group policy, the Domain Group policy will take precedence.

Administrative Templates
========================

Administrative template policies are dynamically read from ADMX/ADML files on
the server.

Windows Settings
================

Policies contained in the "Windows Settings" section of the ``gpedit.msc`` GUI
are statically defined in this module. Each policy is configured for the section
(Machine/User) in the module's _policy_info class. The ``_policy_info`` class
contains a "policies" dict on how the module will configure the policy, where
the policy resides in the GUI (for display purposes), data validation data, data
transformation data, etc.

Current known limitations
=========================

- At this time, start/shutdown scripts policies are displayed, but are not
  configurable.
- Not all "Security Settings" policies exist in the _policy_info class

:depends:
  - pywin32 Python module
  - lxml
  - uuid
  - struct
  - salt.utils.win_reg
�N)�CommandExecutionError�SaltInvocationError)�deserialize)�
CLASS_INFO�REG_POL_HEADER�read_reg_pol_file�search_reg_pol�write_reg_pol_data�lgpo�set_�set)TFF)�etree)�RegistryTz .//*[local-name() = "trueValue"]z!.//*[local-name() = "falseValue"]z.//*[local-name() = "elements"]z#.//*[local-name() = "enabledValue"]z$.//*[local-name() = "disabledValue"]z".//*[local-name() = "enabledList"]z#.//*[local-name() = "disabledList"]z.//*[local-name() = "value"]z.//*[local-name() = "trueList"]z .//*[local-name() = "falseList"]z//*[@key = $keyvalue]z$ancestor::*[local-name() = "policy"]zv//*[local-name() = "policy" and (@*[local-name() = "class"] = "Both" or @*[local-name() = "class"] = $registry_class)]zQ//*[local-name() = $displayNameType and @*[local-name() = "id"] = $displayNameId]z .//*[local-name() = "valueList"]zP.//*[local-name() = "item" and @*[local-name() = "displayName" = $display_name]]z�//*[local-name() = "policy" and @*[local-name() = "name"] = $policy_name and (@*[local-name() = "class"] = "Both" or @*[local-name() = "class"] = $registry_class)]zB//*[starts-with(text(), $policy_name) and @*[local-name() = "id"]]z�//*[local-name() = "policy" and @*[local-name() = "displayName"] = $display_name and (@*[local-name() = "class"] = "Both" or @*[local-name() = "class"] = $registry_class) ]z*ancestor::*[local-name() = "presentation"]z.//*[local-name() = "text"]�en_US�_�-c@s,eZdZdZdd�Zedd��Zedd��Zedd	��Zed
d��Z	edd
��Z
edd��Zedd��Zedd��Z
edd��Zedd��Zedd��Zedd��Zedd��Zedd��Zed d!��Zed"d#��Zed$d%��Zed&d'��Zed(d)��Zed*d+��Zed,d-��Zed.d/��Zed0d1��Zd2S)3�_policy_infoam
    Policy Helper Class
    ===================

    The format of the policy dict is as follows:

    The top most two key/value pairs in the dict divide the policies object into
    the two sections of local group policy, using the keys "Machine" and "User".
    The value make-up of these dicts are described below in "Policy Section
    Definition"

    Policy Section Definition
    -------------------------

    A policy section dict has two required key/value pairs:

    ============  ==============================================================
    Key
    ============  ==============================================================
    lgpo_section  String matching how the policy section is displayed in the mmc
                  snap-in ("Computer Configuration" for "Machine" and "User
                  Configuration" for "User")
    policies      a dict containing the non-Administrative template policy
                  definitions, the key for each item is a short/unique
                  identifier for the policy, the value is described below in
                  "Policies Definition"
    ============  ==============================================================

    Policies Definition
    -------------------

    A policies definition item describes the particular policy. There are three
    child key/value pairs shared with all policy types:

    ============  ==============================================================
    Key           Value
    ============  ==============================================================
    lgpo_section  A list containing the hierarchical path to the policy in the
                  gpedit mmc snap-in.
    Policy        A string containing the name of the policy in the gpedit mmc
                  snap-in
    Settings      An object which describes valid settings for the policy. This
                  can be None for no validation, a list of possible settings, or
                  a dict with the following key/value pairs:

                  - **Function:** The class function to use to validate the
                    setting
                  - **Args:** A dict of kwargs to pass to the class function
    ============  ==============================================================

    Additionally, each policies definition will contain a key/value pair that
    defines the mechanism that will be used to configure the policy. The
    available mechanisms are:  NetUserModal, Registry, Secedit, and LsaRights

    Registry Mechanism
    ------------------

    Some policies simply set values in the Windows registry. The value of this
    key is a dict with the following make-up:

    =====  =====================================================================
    Key    Value
    =====  =====================================================================
    Hive   A string containing the Registry hive, such as ``HKEY_LOCAL_MACHINE``
    Path   A string containing the registry key path, such as
           ``SYSTEM\\CurrentControlSet\\Control\\Lsa``
    Value  A string containing the name of the registry value, such as
           **restrictanonymous**
    Type   A string containing the registry type of the value, such as
           ``REG_DWORD``
    =====  =====================================================================

    Secedit Mechanism
    -----------------

    Some policies are configurable via the "secedit.exe" executable. The value
    of this key is a dict with the following make-up:

    =======  ===================================================================
    Key      Value
    =======  ===================================================================
    Option   A string containing the name of the policy as it appears in an
             export from secedit, such as **PasswordComplexity**
    Section  A string containing the name of the section in which the "Option"
             value appears in an export from ``secedit``, such as "System
             Access"
    =======  ===================================================================

    LsaRights Mechanism
    -------------------

    LSA Rights policies are configured via the LsaRights mechanism. The value of
    this key is a dict with the following make-up:

    ======  ====================================================================
    Key     Value
    ======  ====================================================================
    Option  A string containing the programmatic name of the Lsa Right, such as
            **SeNetworkLogonRight**
    ======  ====================================================================

    NetUserModal Mechanism
    ----------------------

    Some policies are configurable by the **NetUserModalGet** and
    **NetUserModalSet** function from pywin32.  The value of this key is a dict
    with the following make-up:

    ======  ====================================================================
    Key     Value
    ======  ====================================================================
    Modal   The modal "level" that the particular option is specified in (0-3),
            see `here <https://msdn.microsoft.com/en-us/library/windows/desktop/
            aa370656(v=vs.85).aspx>`_
    Option  The name of the structure member which contains the data for the
            policy, for example **max_passwd_age**
    ======  ====================================================================

    NetSH Mechanism
    ---------------

    The firewall policies are configured by the ``netsh.exe`` executable. The
    value of this key is a dict with the following make-up:

    =======  ===================================================================
    Key      Value
    =======  ===================================================================
    Profile  The firewall profile to modify. Can be one of Domain, Private, or
             Public
    Section  The section of the firewall to modify. Can be one of state,
             firewallpolicy, settings, or logging.
    Option   The setting within that section
    Value    The value of the setting
    =======  ===================================================================

    More information can be found in the advfirewall context in netsh. This can
    be access by opening a netsh prompt. At a command prompt type the following:

    c:\>netsh
    netsh>advfirewall
    netsh advfirewall>set help
    netsh advfirewall>set domain help

    AdvAudit Mechanism
    ------------------

    The Advanced Audit Policies are configured using a combination of the
    auditpol command-line utility and modifying the audit.csv file in two
    locations. The value of this key is a dict with the following make-up:

    ======  ===================================
    Key     Value
    ======  ===================================
    Option  The Advanced Audit Policy to modify
    ======  ===================================

    Transforms
    ----------

    Optionally, each policy definition can contain a "Transform" key. The
    Transform key is used to handle data that is stored and viewed differently.
    This key's value is a dict with the following key/value pairs:

    ===  =======================================================================
    Key  Value
    ===  =======================================================================
    Get  The name of the class function to use to transform the data from the
         stored value to how the value is displayed in the GUI
    Put The name of the class function to use to transform the data supplied by
        the user to the correct value that the policy is stored in
    ===  =======================================================================

    For example, "Minimum password age" is stored in seconds, but is displayed
    in days.  Thus the "Get" and "Put" functions for this policy do these
    conversions so the user is able to set and view the policy using the same
    data that is shown in the GUI.
    cCs�4ddddddd�|_ddddd	d
�|_ddd
dddd�|_ddddddddd�|_dddddd�|_ddddd�|_dd|jdd�|jdd�d �|_d!ddddd"�|_dd|jdd�|jdd�d �|_dd|jdd�|jdd�d �|_	ddddd#�|_
dd|j
dd�|j
dd�d �|_gd$�|_gd%�|_
gd&�|_gd'�|_gd(�|_gd)�|_gd*�|_d+d,d-ddd�|_d.d/d0ddd"�|_d1d2ddd3�|_d4d5d6ddd"�|_d7d8d9ddd:�|_d;d<ddd�|_d=d>d?ddd"�|_d@dAdBdCdD�|_dEdFdCdG�|_dHdIdCdJ�|_dKdLdCdJ�|_dKdIdCdJ�|_dMd4dCdN�|_dOdPdQdRdSdTdUdddV�	|_ dWdXdYdZd[d\ddd�|_!d1d]d2ddd"�|_"dOd^d_ddd`�|_#dadbdcddd"�|_$dadddedfdgdddh�|_%didjdkddd"�|_&dadldmdndodddh�|_'didpdoddd"�|_(dddq�|_)dd|j)dd�|j)dd�d �|_*dridsdtgdu�dvt+j,�-t+�.dw�dxdydzd{d|�d}�d~��dd�gdu�dvt+j,�-t+�.dw�dxdydzd{d��d}�d~��d�d�gdu�t+j,�-t+�.dw�dxdydzd{d��d�d�gd��d��d�d�d��d���d�d�gd��d�t+j,�-t+�.dw�dxdydzd{d|�d}�d~��d�d�gd��d�t+j,�-t+�.dw�dxdydzd{d��d}�d~��d�d�gd��t+j,�-t+�.dw�dxdydzd{d��d�d�gd��d��d�d�d��d���d�d�|j|j)�/�d�d�d��|j*d���d�d�|j|j�/�d�d�d�d�d��|jd���d�d�|jd�d�d�d�d��d�d�id���d�d�|j|j�/�d�d�d�d�d��|jd���d�d�|j|j�/�d�d�d�d�d��|jd���d�d�|j|j�/�d�d�d�d�d��|jd���d�d�|jd�d�d�d�d��d�d�d��d���d�d�|jd�d�dzd�d��d�d�d��d���d�d�|jd�d�dzd�d��d�d�d��d���d�d�|j|j�/�d�d�d�d�d��|jd���d�d�|jd�d�d�d�d��d�d�d��d���id�d�|j|j�/�d�d�d�d�d��dd|jdd�|jdd�d �d���d�d�|j
|j�/�d�d�d�dȜdd|jdd�|jdd�d �dɜ�d�d�|j
|j�/�d�d�d�dȜdd|jdd�|jdd�d �dɜ�d�d�|j
|j�/�d�d�d�dȜdd|jdd�|jdd�d �dɜ�d�d�|j
|j�/�d�d�d�dȜdd|jdd�|jdd�d �dɜ�d�d�|j
|j�/�d�d�d�dȜdd|jdd�|jdd�d �dɜ�d�d�|j
|j�/�d�d�d�dȜdd|jdd�|jdd�d �dɜ�d�d�|j
|j�/�d�d�d�dȜdd|jdd�|jdd�d �dɜ�d�d�|j
|j�/�d�d�d�dȜdd|jdd�|jdd�d �dɜ�d�d�|j
|j�/�d�d�d�dȜdd|jdd�|jdd�d �dɜ�d�d�|j
|j�/�d�d�d�dȜdd|jdd�|jdd�d �dɜ�d�d�|j
|j�/�d�d�d�dȜdd|jdd�|jdd�d �dɜ�d�d�|j
|j�/�d�d�d�dȜdd|jdd�|jdd�d �dɜ�d�d�|j
|j�/�d�d�d�dȜdd|jdd�|jdd�d �dɜ�d�d�|j
|j�/�d�d�d�dȜdd|jdd�|jdd�d �dɜ�d�d�|j
|j�/�d�d�d�dȜdd|jdd�|jdd�d �dɜ�d�d�|j
|j�/�d�d�d�dȜdd|jdd�|jdd�d �dɜ��id�d�|j
|j�/�d�d�d�dȜdd|jdd�|jdd�d �dɜ�d�d�|j
|j�/�d�d�d�dȜdd|jdd�|jdd�d �dɜ�d�d�|j
dd�d�d�dȜd���d�d�|j
dd�d�d�dȜd���d�d�|j
dd�d�d�dȜd���d�d�|j
dd�d��ddȜd����d�d|j
dd�d��ddȜd����d�d|j
dd�d��ddȜd����d�d|j
|j�/�d�d��ddȜdd|jdd�|jdd�d �dɜ��d�d	|j
|j�/�d�d��ddȜdd|jdd�|jdd�d �dɜ��d
�d|j
|j�/�d�d��ddȜdd|jdd�|jdd�d �dɜ��d�d
|j
|j�/�d�d��ddȜdd|jdd�|jdd�d �dɜ��d�d|j
|j�/�d�d��ddȜdd|jdd�|jdd�d �dɜ��d�d|j
|j�/�d�d��ddȜdd|jdd�|jdd�d �dɜ��d�d|j�d�d�d�d��d��d�d�d��d���d�d|j�d�d�d �d!�d"��d��d�d#�d��d$�d%�d&�d!i�d&�d!id ��d'���d(�d)|j�d�d�d �d��d��d�d*�d��d$�d%d���d'���i�d+�d,|j�d�d�d-�d��d��d�d.�d��d���d/�d0|j|j)�/��d/d�d��|j*d����d1�d2|j|j)�/��d3d�d��|j*d����d4�d5|j|j�/�d��d6�d4d�d��|jd����d7�d8|j)�/�|j�d9d�d��|j*�d:���d;�d<|j�/�|jd��d=�d;d�d��dd|jdd�|jdd�d ��d>���d?�d@|j)�/�|j�dAd�d��|j*�d:���dB�dC|j|j�/�d�d��dDd�d��|jd����dE�dFd|j�dGd�d���dH�dId���d:���dJ�dKd|j�dLd�d���dH�dId���d:���dM�dN|j�/�|jd�d��dMd�d��|j�d>���dO�dP|j�/�|jd�d��dQd�d��|j�d>���dR�dS|j�/�|jd��dT�dRd�d��|j�d>���dU�dV�d�d�dW�d��d�|jd��dX�dUd�d���dY���dZ�d[|j�/�|jd��dX�dZd�d��|j�d>���d\�d]|j�/�|jd��dX�d\d�d��dd|jdd�|jdd�d ��d>���d^�d_|j�/�|jd��dT�d^d�d��|j�d>���i�d`�da|j�/�|jd��dT�d`d�d��|j�d>���db�dc|j�/�|jd��dT�dbd�d��|j�d>���dd�de|j�/�|jd��dT�ddd�d��dd|jdd�|jdd�d ��d>���df�dg|j�/�|jd��dT�dfd�d��dd|jdd�|jdd�d ��d>���dh�di|j�/�|jd��dT�dhd�d��|j�d>���dj�dk|j�/�|jd��dT�djd�d��|j�d>���dl�dm|j�/�|jd��dT�dld�d��|j�d>���dn�do|j�/�|jd��dT�dnd�d��|j�d>���dp�dq|j�/�|jd��dT�dpd�d��|j�d>���dr�ds|j�/�|jd��dT�drd�d��|j�d>���dt�du�d�d�dv�d��d�|jd��dX�dtd�d���dY���dw�dx�d�d�dv�d��d�|jd��d=�dwd�d���dY���dy�dz�d�d�d{�d��d�|jd��d=�dyd�d���dY���d|�d}|jd��d=�d|d�d��d�d�id����d~�d|jd��d=�d~d�d��d�d�id����d��d�|j�/�|jd��d=�d�d�d��dd|jdd�|jdd�d ��d>���d��d�|j�/�|jd��dT�d�d�d��|j�d>���i�d��d�|j�/�|jd��d��d�d�d��|j�d>���d��d�|j�/�|jd��d��d�d�d��|j�d>���d��d�|j�/�|jd��d��d�d�d��|j�d>���d��d��d�d�d��d��d�|jd�d��d�d�d���dY���d��d�|j�/�|jd�d��d�d�d��dd|jdd�|jdd�d ��d>���d��d�|j�/�|jd�d��d�d�d��|j�d>���d��d�|j�/�|jd�d��d�d�d��|j�d>���d��d�|j�/�|jd�d��d�d�d��|j�d>���d��d�|j�/�|jd�d��d�d�d��dd|jdd�|jdd�d ��d>���d��d�t0�d�t0�d�g|jd�d��d��d�d���d��d�d���d>���d��d�|j�/�|jd�d��d�d�d��|j�d>���d��d�|j�/�|jd��dT�d�d�d��|j�d>���d��d�|j
�/�|jd��d��d�d�d��|j�d>���d��d�g�d��|jd��dX�d�d�d���d��d�d���d>���d��d�|j
�/�|jd��dX�d�d�d��|j�d>���d��d�|j
�/�|jd��dX�d�d�d��|j�d>���d��d��d��d�t0�d��d�t0�d��g|j�d��d�d���d��d�d���d:���i�d��d�|j
�/�|jd�d��d�d�d��|j�d>���d��d�|jd��d��d�d�d��d�d�id����d��d�|j�/�|jd��d��d�d�d��dd|jdd�|jdd�d ��d>���d��d�|j�/�|jd��d��d�d�d��dd|jdd�|jdd�d ��d>���dd�|j
�/�|jd��d��d�d�d��|j�d>���dĐd�|j
�/�|jd��dƐd�d�d��|j�d>���dǐd�|j
�/�|jd��dƐd�d�d��|j�d>���dɐd�|j
�/�|jd��dƐd�d�d��|j�d>���dːd�|j
�/�|jd��dƐd�d�d��|j�d>���d͐dΐd�d�dv�d��d�|jd��dƐd�d�d���dY���dϐd�|j
�/�|jd��dƐd�d�d��|j�d>���dѐd�|j�d�d�dӐd!�d"��d��dԐdՐd��d֐dאd&�d!i�d&�d!id ��d'���dؐd�|j�d�d�dڐd��d��dԐdېd��d���dܐd�|j�d�d�dӐd��d��dԐdސd��d֐d�d���d'���dߐd�|j|j�/��dߐd�d��|jd����d�d�|j|j�/��d�d�d��|jd����d�d�|j|j�/��d�d�d��|jd����i�d�d�|j|j�/��d�d�d��|jd����d�d�|j|j�/��d�d�d��|jd����d�d�|j|j�/��d�d�d��|jd����d�d�|j|j�/��d�d�d��|jd����d�d�|j|j�/��d�d�d��|jd����d�d�|j|j�/��d�d�d��|jd����d�d�|j|j�/��d�d�i|j	�d����d��d�|j|j�/��d�d�i|j	�d����d��d�|j|j�/��d�d�i|j	�d����d��d�|j|j�/��d�d�i|j	�d����d��d�|j|j�/��d�d�i|j	�d����d��d�|j|j�/��d�d�i|j	�d����d�d|j|j�/��d�di|j	�d����d�d|j|j�/��d�di|j	�d����d�d|j|j�/��d�di|j	�d����d�d|j|j�/��d�di|j	�d����d�d	|j|j�/��d�d	i|j	�d����i�d
�d|j|j�/��d�di|j	�d����d�d
|j|j�/��d�d
i|j	�d����d�d|j|j�/��d�di|j	�d����d�d|j|j�/��d�di|j	�d����d�d|j|j�/��d�di|j	�d����d�d|j|j�/��d�di|j	�d����d�d|j|j�/��d�di|j	�d����d�d|j|j�/��d�di|j	�d����d�d|j|j�/��d�di|j	�d����d�d|j|j�/��d�di|j	�d����d�d|j|j�/��d�di|j	�d����d �d!|j|j�/��d�d!i|j	�d����d"�d#|j|j�/��d�d#i|j	�d����d$�d%|j|j�/��d�d%i|j	�d����d&�d'|j|j�/��d�d'i|j	�d����d(�d)|j|j�/��d�d)i|j	�d����d*�d+|j|j�/��d�d+i|j	�d����i�d,�d-|j|j�/��d�d-i|j	�d����d.�d/|j|j�/��d�d/i|j	�d����d0�d1|j|j�/��d�d1i|j	�d����d2�d3|j|j�/��d�d3i|j	�d����d4�d5|j|j�/��d�d5i|j	�d����d6�d7|j|j�/��d�d7i|j	�d����d8�d9|j|j�/��d�d9i|j	�d����d:�d;|j|j�/��d�d;i|j	�d����d<�d=|j|j�/��d�d=i|j	�d����d>�d?|j|j�/��d�d?i|j	�d����d@�dA|j|j�/��d�dAi|j	�d����dB�dC|j|j�/��d�dCi|j	�d����dD�dE|j|j�/��d�dEi|j	�d����dF�dG|j|j�/��d�dGi|j	�d����dH�dI|j|j�/��d�dIi|j	�d����dJ�dK|j|j�/��d�dKi|j	�d����dL�dM|j|j�/��d�dMi|j	�d����i�dN�dO|j|j�/��d�dOi|j	�d����dP�dQ|j|j�/��d�dQi|j	�d����dR�dS|j|j�/��d�dSi|j	�d����dT�dU|j|j�/��d�dUi|j	�d����dV�dW|j|j�/��d�dWi|j	�d����dX�dY|j|j�/��d�dYi|j	�d����dZ�d[|j|j�/��d�d[i|j	�d����d\�d]|j|j�/��d�d]i|j	�d����d^�d_|j|j�/��d�d_i|j	�d����d`�da|j|j�/��d�dai|j	�d����db�dc|j|j�/��d�dci|j	�d����dd�de|j|j�/��d�dei|j	�d����df�dg|j|j�/��d�dgi|j	�d����dh�di|j|j�/��d�dii|j	�d����dj�dk|jdd�d�dji�dl�dmd���dn���do�dp|jdd�d�doi�dl�dmd���dn���dq�dr|jdd�d�dqi�dl�dmd���dn���i�ds�dt|jdd�d�dsi�dl�dmd���dn���du�dv|jdd�d�dui�dl�dmd���dn���dw�dx|jdd�d�dwi�dl�dmd���dn���dy�dz|jdd�d�dyi�dl�dmd���dn���d{�d||jdd�d�d{i�dl�dmd���dn���d}�d~|jdd�d�d}i�dl�dmd���dn���d�d�|jdd�d�di�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���i�d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���d��d�d|jd�d�d�i�dl�dmd���d����d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���i�d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���d��d�|jdd�d�d�i�dl�dmd���dn���dd�|jdd�d�d�i�dl�dmd���dn���dĐd�|jdd�d�d�i�dl�dmd���dn���dƐd�|j�/�|jd��dȐd�d�d��|j�d>���dʐd�|j�/�|jd��dȐd�d�d��|j�d>���d͐d�|j�/�|jd��dϐd�d�d��dd|jdd�|jdd�d ��d>���dАd�|j�/�|jd��d�dd�d��|j�d>���dӐd�d|jd��dՐd�d�d��d�d�i�d>���d֐d�d|jd��dՐd�d�d��d�d�i�d>���dؐd�|j�/�|jd�d��d�d�d��|j�d>���dڐd�|j�/�|jd��dܐd�d�d��|j�d>���dݐd�|j�/�|jd��dߐd�d�d��|j�d>���d�d�d|jd��d�d�d�d���d�d�|j dd�|j dd�d ��d>���i�d�d�|j�/�|jd�d��d�d�d��|j�d>���d�d�|j|j)�/��d�d�d��|j*d����d�d�|j!�/�|jd�d��d�d�d��dd|j!dd�|j!dd�d ��d>���d�d�|j"�/�|jd��d�d�d�d��dd|j"dd�|j"dd�d ��d>���d�d�d|jd��d�d�d�d���d�d�|j#dd�|j#dd�d ��d>���d�d�d|jd��d�d�d�d���d�d�|j#dd�|j#dd�d ��d>���d�d�|jd��d�d�d�d��d�d�d��d����d��d�|jd��dƐd�d�d��d�d�d��d����d��d�|j$�/�|jd��d��d�d�d��dd|j$dd�|j$dd�d ��d>���d��d�|j%�/�|jd��d��d�d�d��dd|j%dd�|j%dd�d ��d>���d��d�|j&�/�|jd��d��d�d�d��dd|j&dd�|j&dd�d ��d>���d��d�|j'�/�|jd��d��d�d�d��dd|j'dd�|j'dd�d ��d>���d�d|j(�/�|jd��dܐdd�d��dd|j(dd�|j(dd�d ��d>���d�d|j�/�|jd��d=�dd�d��|j�d>���d�d|j�/�|jd��d�dd�d��|j�d>���d�d|j�/�|jd��d	�dd�d��|j�d>���d
�d|j�/�|jd��d�d
d�d��|j�d>����d
|jd��d�dd�d��d�d�d��d���d|j�/�|jd��d�dd�d��|j�d>��d���d��di�d��d�|_1dS(NzNo auditing�Success�FailurezSuccess, Failure�Not Defined)r���rN�No Auditing�Success and Failure�Not Configured)rrrrNz	No ActionzLock WorkstationzForce Logoffz/Disconnect if a Remote Desktop Services session)�0�1�2�3N�(value not set)zElevate without promptingz,Prompt for credentials on the secure desktopz(Prompt for consent on the secure desktopzPrompt for credentialszPrompt for consentz+Prompt for consent for non-Windows binaries)rrrr��Nr z%Automatically deny elevation requests)rrrNr �Disabled�Enabled)rrNr �_dict_lookupF)�lookup�value_lookupT)�Get�PutZGetArgsZPutArgsZDefault)rrrNr )rrNr )�Computer Configuration�Windows Settings�Security Settings�Local PolicieszSecurity Options)r*r+r,z'Windows Firewall with Advanced SecurityzCWindows Firewall with Advanced Security - Local Group Policy Object)r*r+r,�Account PolicieszPassword Policy)r*r+r,r-zAudit Policy)r*r+r,z#Advanced Audit Policy Configurationz1System Audit Policies - Local Group Policy Object)r*r+r,r.zAccount Lockout Policy)r*r+r,r-zUser Rights AssignmentzThis policy is disabledz"Users can't add Microsoft accountsz1Users can't add or log on with Microsoft accountsZNeverzWhen supportedZAlways�NonezRequire signing)rrNr ZOffzAccept if provided by clientzRequired from clientz(User display name, domain and user nameszUser display name onlyzDo not display user information)rrrNr z0Classic - local users authenticate as themselvesz.Guest only - local users authenticate as Guestz<User input is not required when new keys are stored and usedz+User is prompted when the key is first usedz3User must enter a password each time they use a keyzBlock (default)zBlock all connectionsZAllow�Not configured)ZblockinboundZblockinboundalwaysZallowinbound�
notconfiguredZBlockzAllow (default))Z
blockoutboundZ
allowoutboundr1z
Yes (default)ZNo)�enable�disabler1ZYeszNo (default)zOn (recommended))�onZoffr1z
No minimumZDES_CBC_CRCZDES_CBD_MD5ZRC4_HMAC_MD5ZAES128_HMAC_SHA1ZAES256_HMAC_SHA1zFuture Encryption Types)	rrrr!��i�Nr zSend LM & NTLM responsez:Send LM & NTLM - use NTLMv2 session security if negotiatedzSend NTLM response onlyzSend NTLMv2 response onlyz$Send NTLMv2 response only. Refuse LMz+Send NTLMv2 response only. Refuse LM & NTLMzNegotiate signingzRequire NTLMv2 session securityzRequire 128-bit encryption)rii Nr ZDisablez#Enable auditing for domain accountsz Enable auditing for all accountsz,Enable for domain accounts to domain serverszEnable for domain accountszEnable for domain serversz
Enable all)rrrr"�Nr z	Allow allzDeny all domain accountszDeny all accountsz*Deny for domain accounts to domain serverszDeny for domain accountszDeny for domain serverszDeny allz	Audit all)rrr*ZStartupScriptszStartup Scripts)r*r+�Scripts (Startup/Shutdown)�Startupr9�WINDIR�System32�GroupPolicy�Machine�Scripts�scripts.ini)�Section�IniPath)�Policy�lgpo_section�	ScriptIniZStartupPowershellScriptszStartup Powershell Scripts�
psscripts.iniZStartupPowershellScriptOrderz:Startup - For this GPO, run scripts in the following orderZ
ScriptsConfigZStartExecutePSFirst)�true�falseN)rAr@�SettingName�Settings�#_powershell_script_order_conversion�+_powershell_script_order_reverse_conversion)r(r))rBrCrD�	TransformZShutdownScriptszShutdown Scripts)r*r+r8�ShutdownrMZShutdownPowershellScriptszShutdown Powershell ScriptsZShutdownPowershellScriptOrderz;Shutdown - For this GPO, run scripts in the following orderZEndExecutePSFirstZLSAAnonymousNameLookupz4Network access: Allow anonymous SID/Name translation�
System Access)�Optionr@)rBrCrI�SeceditrLZRestrictAnonymousSamzBNetwork access: Do not allow anonymous enumeration of SAM accounts�HKEY_LOCAL_MACHINEz$SYSTEM\CurrentControlSet\Control\Lsa�	REG_DWORD)�Hive�Path�Value�Type)rBrCrIrrLZRestrictRemoteSAMzDNetwork access: Restrict clients allowed to make remote calls to SAMz$System\CurrentControlSet\Control\Lsa�REG_SZr)�_string_put_transform)rBrCrrLZRestrictAnonymouszMNetwork access: Do not allow anonymous enumeration of SAM accounts and sharesZDisableDomainCredsz\Network access: Do not allow storage of passwords and credentials for network authenticationZEveryoneIncludesAnonymouszANetwork access: Let Everyone permissions apply to anonymous usersZeveryoneincludesanonymousZNullSessionPipesz<Network access: Named Pipes that can be accessed anonymouslyz9SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters�REG_MULTI_SZ�_multi_string_put_transform�_multi_string_get_transform)r)r(ZRemoteRegistryExactPathsz2Network access: Remotely accessible registry pathszKSYSTEM\CurrentControlSet\Control\SecurePipeServers\winreg\AllowedExactPathsZRemoteRegistryPathsz@Network access: Remotely accessible registry paths and sub-pathszFSYSTEM\CurrentControlSet\Control\SecurePipeServers\winreg\AllowedPathsZRestrictNullSessAccesszCNetwork access: Restrict anonymous access to Named Pipes and Sharesz9System\CurrentControlSet\Services\LanmanServer\ParametersZNullSessionSharesz7Network access: Shares that can be accessed anonymouslyZ
ForceGuestz=Network access: Sharing and security model for local accountsZWfwDomainStatezNetwork firewall: Domain: State�domain�state�State)�Profiler@rO)rBrCrI�NetSHrLZWfwPrivateStatez Network firewall: Private: StateZprivateZWfwPublicStatezNetwork firewall: Public: StateZpublicZWfwDomainInboundConnectionsz-Network firewall: Domain: Inbound connections�firewallpolicy�InboundZWfwPrivateInboundConnectionsz.Network firewall: Private: Inbound connectionsZWfwPublicInboundConnectionsz-Network firewall: Public: Inbound connectionsZWfwDomainOutboundConnectionsz.Network firewall: Domain: Outbound connections�OutboundZWfwPrivateOutboundConnectionsz/Network firewall: Private: Outbound connectionsZWfwPublicOutboundConnectionsz.Network firewall: Public: Outbound connectionsZWfwDomainSettingsNotificationz:Network firewall: Domain: Settings: Display a notification�settingsZInboundUserNotificationZWfwPrivateSettingsNotificationz;Network firewall: Private: Settings: Display a notificationZWfwPublicSettingsNotificationz:Network firewall: Public: Settings: Display a notificationZ#WfwDomainSettingsLocalFirewallRulesz>Network firewall: Domain: Settings: Apply local firewall rulesZLocalFirewallRulesZ$WfwPrivateSettingsLocalFirewallRulesz?Network firewall: Private: Settings: Apply local firewall rulesZ#WfwPublicSettingsLocalFirewallRulesz>Network firewall: Public: Settings: Apply local firewall rulesZ%WfwDomainSettingsLocalConnectionRuleszINetwork firewall: Domain: Settings: Apply local connection security rulesZLocalConSecRulesZ&WfwPrivateSettingsLocalConnectionRuleszJNetwork firewall: Private: Settings: Apply local connection security rulesZ%WfwPublicSettingsLocalConnectionRuleszINetwork firewall: Public: Settings: Apply local connection security rulesZWfwDomainLoggingNamez'Network firewall: Domain: Logging: Name�logging�FileName)rBrCrIr`ZWfwPrivateLoggingNamez(Network firewall: Private: Logging: NameZWfwPublicLoggingNamez'Network firewall: Public: Logging: NameZWfwDomainLoggingMaxFileSizez2Network firewall: Domain: Logging: Size limit (KB)�MaxFileSizeZWfwPrivateLoggingMaxFileSizez3Network firewall: Private: Logging: Size limit (KB)ZWfwPublicLoggingMaxFileSizez2Network firewall: Public: Logging: Size limit (KB)Z"WfwDomainLoggingAllowedConnectionsz=Network firewall: Domain: Logging: Log successful connectionsZLogAllowedConnectionsZ#WfwPrivateLoggingAllowedConnectionsz>Network firewall: Private: Logging: Log successful connectionsZ"WfwPublicLoggingAllowedConnectionsz=Network firewall: Public: Logging: Log successful connectionsZ"WfwDomainLoggingDroppedConnectionsz6Network firewall: Domain: Logging: Log dropped packetsZLogDroppedConnectionsZ#WfwPrivateLoggingDroppedConnectionsz7Network firewall: Private: Logging: Log dropped packetsZ"WfwPublicLoggingDroppedConnectionsz6Network firewall: Public: Logging: Log dropped packetsZPasswordHistoryzEnforce password history�_in_range_inclusiver�)�min�max)�Function�ArgsZpassword_hist_len)�ModalrO)rBrCrI�NetUserModalZMaxPasswordAgezMaximum password ageri�
%���)rjrk�
zero_valueZmax_passwd_age�_seconds_to_days�_days_to_secondsrq)rBrCrIrorLZMinPasswordAgezMinimum password ageZmin_passwd_ageZMinPasswordLenzMinimum password length�Zmin_passwd_lenZPasswordComplexityz*Password must meet complexity requirementsZClearTextPasswordsz+Store passwords using reversible encryptionZClearTextPasswordZ RelaxMinimumPasswordLengthLimitsz$Relax minimum password length limitsz$SYSTEM\CurrentControlSet\Control\SAMZAdminAccountStatusz&Accounts: Administrator account statusZEnableAdminAccount)rBrIrCrPrLZNoConnectedUserz"Accounts: Block Microsoft accountsz9SOFTWARE\Microsoft\Windows\CurrentVersion\policies\system)rBrIrCrrLZGuestAccountStatuszAccounts: Guest account statusZEnableGuestAccountZLimitBlankPasswordUsezJAccounts: Limit local account use of blank passwords to console logon onlyZlimitblankpassworduseZRenameAdministratorAccountz&Accounts: Rename administrator accountZNewAdministratorName�
_strip_quotes�_add_quotesZRenameGuestAccountzAccounts: Rename guest accountZNewGuestNameZAuditBaseObjectsz0Audit: Audit the access of global system objectsZSceNoApplyLegacyAuditPolicyzrAudit: Force audit policy subcategory settings (Windows Vista or later) to override audit policy category settingsZSCENoApplyLegacyAuditPolicyZDontDisplayLastUserNamez0Interactive logon: Do not display last user namez9Software\Microsoft\Windows\CurrentVersion\Policies\SystemZCachedLogonsCountzbInteractive logon: Number of previous logons to cache (in case domain controller is not available)�2z5Software\Microsoft\Windows NT\CurrentVersion\Winlogon)rBrIrCrZForceUnlockLogonzQInteractive logon: Require Domain Controller authentication to unlock workstationZScRemoveOptionz.Interactive logon: Smart card removal behaviorZ
DisableCADz.Interactive logon: Do not require CTRL+ALT+DELZFilterAdministratorTokenzPUser Account Control: Admin Approval Mode for the built-in Administrator accountZEnableUIADesktopTogglezjUser Account Control: Allow UIAccess applications to prompt for elevation without using the secure desktopZConsentPromptBehaviorAdminz`User Account Control: Behavior of the elevation prompt for administrators in Admin Approval ModeZConsentPromptBehaviorUserzIUser Account Control: Behavior of the elevation prompt for standard usersZEnableInstallerDetectionzOUser Account Control: Detect application installations and prompt for elevationZValidateAdminCodeSignatureszLUser Account Control: Only elevate executables that are signed and validatedZEnableSecureUIAPathsz_User Account Control: Only elevate UIAccess applications that are installed in secure locationsZ	EnableLUAzCUser Account Control: Run all administrators in Admin Approval ModeZPromptOnSecureDesktopzOUser Account Control: Switch to the secure desktop when prompting for elevationZEnableVirtualizationzWUser Account Control: Virtualize file and registry write failures to per-user locationsZPasswordExpiryWarningzCInteractive logon: Prompt user to change password before expirationi�ZMaxDevicePasswordFailedAttemptsz4Interactive logon: Machine account lockout thresholdZInactivityTimeoutSecsz+Interactive logon: Machine inactivity limiti�'	Zlegalnoticetextz>Interactive logon: Message text for users attempting to log onZlegalnoticecaptionz?Interactive logon: Message title for users attempting to log onZDontDisplayLockedUserIdzFInteractive logon: Display user information when the session is lockedZ
ScForceOptionz%Interactive logon: Require smart cardZClient_RequireSecuritySignaturez@Microsoft network client: Digitally sign communications (always)z>SYSTEM\CurrentControlSet\Services\LanmanWorkstation\ParametersZRequireSecuritySignatureZClient_EnableSecuritySignaturezJMicrosoft network client: Digitally sign communications (if server agrees)ZEnableSecuritySignatureZEnablePlainTextPasswordzNMicrosoft network client: Send unencrypted password to third-party SMB serversZAutoDisconnectzPMicrosoft network server: Amount of idle time required before suspending sessioni��ZEnableS4U2SelfForClaimszFMicrosoft network server: Attempt S4U2Self to obtain claim informationZServer_RequireSecuritySignaturez@Microsoft network server: Digitally sign communications (always)ZServer_EnableSecuritySignaturezJMicrosoft network server: Digitally sign communications (if client agrees)ZEnableForcedLogoffzDMicrosoft network server: Disconnect clients when logon hours expireZSmbServerNameHardeningLevelzAMicrosoft network server: Server SPN target name validation levelZFullPrivilegeAuditingz4Audit: Audit the use of Backup and Restore privilegeZ
REG_BINARY�*_binary_enable_zero_disable_one_conversion�2_binary_enable_zero_disable_one_reverse_conversionZCrashOnAuditFailzDAudit: Shut down system immediately if unable to log security auditsZUndockWithoutLogonz.Devices: Allow undock without having to log onZAddPrinterDriversz6Devices: Prevent users from installing printer driverszNSystem\CurrentControlSet\Control\Print\Providers\LanMan Print Services\ServersZAllocateDASDz4Devices: Allowed to format and eject removable media)�9999rrr�_dasd_conversion�_dasd_reverse_conversionZAllocateCDRomsz>Devices: Restrict CD-ROM access to locally logged-on user onlyZAllocateFloppiesz>Devices: Restrict floppy access to locally logged-on user onlyZDriverSigningPolicyz.Devices: Unsigned driver installation behaviorz3,0z3,rz0MACHINE\Software\Microsoft\Driver Signing\Policy�Registry Values�_driver_signing_reg_conversion�&_driver_signing_reg_reverse_conversionZ
SubmitControlz;Domain controller: Allow server operators to schedule tasksZVulnerableChannelAllowListzGDomain controller: Allow vulnerable Netlogon secure channel connectionsz5SYSTEM\CurrentControlSet\Services\Netlogon\ParametersZLdapEnforceChannelBindingzADomain controller: LDAP server channel binding token requirementsz1System\CurrentControlSet\Services\NTDS\ParametersZLDAPServerIntegrityz3Domain controller: LDAP server signing requirementsZRefusePasswordChangez:Domain controller: Refuse machine account password changesZRequireSignOrSealzEDomain member: Digitally encrypt or sign secure channel data (always)z5System\CurrentControlSet\Services\Netlogon\ParametersZSealSecureChannelzDDomain member: Digitally encrypt secure channel data (when possible)ZSignSecureChannelzADomain member: Digitally sign secure channel data (when possible)ZDisablePasswordChangez7Domain member: Disable machine account password changesZMaximumPasswordAgez3Domain member: Maximum machine account password ageZRequireStrongKeyzADomain member: Require strong (Windows 2000 or later) session keyZLockoutDurationzAccount lockout durationi��[rZlockout_duration�_seconds_to_minutes�_minutes_to_secondsZLockoutThresholdzAccount lockout thresholdi�Zlockout_thresholdZ
LockoutWindowz#Reset account lockout counter afterZlockout_observation_windowZAuditAccountLogonzAudit account logon events�Event AuditZAuditAccountManagezAudit account managementZ
AuditDSAccesszAudit directory service accessZAuditLogonEventszAudit logon eventsZAuditObjectAccesszAudit object accessZAuditPolicyChangezAudit policy changeZAuditPrivilegeUsezAudit privilege useZAuditProcessTrackingzAudit process trackingZAuditSystemEventszAudit system eventsZAuditCredentialValidationzAudit Credential ValidationrO)rBrCrI�AdvAuditrLZ"AuditKerberosAuthenticationServicez%Audit Kerberos Authentication ServiceZ$AuditKerberosServiceTicketOperationsz(Audit Kerberos Service Ticket OperationsZAuditOtherAccountLogonEventsz Audit Other Account Logon EventsZAuditApplicationGroupManagementz"Audit Application Group ManagementZAuditComputerAccountManagementz!Audit Computer Account ManagementZ AuditDistributionGroupManagementz#Audit Distribution Group ManagementZ!AuditOtherAccountManagementEventsz%Audit Other Account Management EventsZAuditSecurityGroupManagementzAudit Security Group ManagementZAuditUserAccountManagementzAudit User Account ManagementZAuditDPAPIActivityzAudit DPAPI ActivityZAuditPNPActivity�Audit PNP ActivityZAuditProcessCreationzAudit Process CreationZAuditProcessTerminationzAudit Process TerminationZAuditRPCEventszAudit RPC EventsZAuditTokenRightAdjusted�Audit Token Right AdjustedZ(AuditDetailedDirectoryServiceReplicationz,Audit Detailed Directory Service ReplicationZAuditDirectoryServiceAccesszAudit Directory Service AccessZAuditDirectoryServiceChangeszAudit Directory Service ChangesZ AuditDirectoryServiceReplicationz#Audit Directory Service ReplicationZAuditAccountLockoutzAudit Account LockoutZAuditUserDeviceClaimszAudit User / Device ClaimsZAuditGroupMembershipzAudit Group MembershipZAuditIPsecExtendedModezAudit IPsec Extended ModeZAuditIPsecMainModezAudit IPsec Main ModeZAuditIPsecQuickModezAudit IPsec Quick ModeZAuditLogoffzAudit LogoffZ
AuditLogonzAudit LogonZAuditNetworkPolicyServerzAudit Network Policy ServerZAuditOtherLogonLogoffEventszAudit Other Logon/Logoff EventsZAuditSpecialLogonzAudit Special LogonZAuditApplicationGeneratedzAudit Application GeneratedZAuditCertificationServiceszAudit Certification ServicesZAuditDetailedFileSharezAudit Detailed File ShareZAuditFileSharezAudit File ShareZAuditFileSystemzAudit File SystemZ AuditFilteringPlatformConnectionz#Audit Filtering Platform ConnectionZ AuditFilteringPlatformPacketDropz$Audit Filtering Platform Packet DropZAuditHandleManipulationzAudit Handle ManipulationZAuditKernelObjectzAudit Kernel ObjectZAuditOtherObjectAccessEventsz Audit Other Object Access EventsZ
AuditRegistryzAudit RegistryZAuditRemovableStoragezAudit Removable StorageZAuditSAMz	Audit SAMZAuditCentralAccessPolicyStaging�#Audit Central Access Policy StagingZAuditAuditPolicyChangezAudit Audit Policy ChangeZAuditAuthenticationPolicyChangez"Audit Authentication Policy ChangeZAuditAuthorizationPolicyChangez!Audit Authorization Policy ChangeZ"AuditFilteringPlatformPolicyChangez&Audit Filtering Platform Policy ChangeZ AuditMPSSVCRuleLevelPolicyChangez%Audit MPSSVC Rule-Level Policy ChangeZAuditOtherPolicyChangeEventsz Audit Other Policy Change EventsZAuditNonSensitivePrivilegeUsez!Audit Non Sensitive Privilege UseZAuditOtherPrivilegeUseEventsz Audit Other Privilege Use EventsZAuditSensitivePrivilegeUsezAudit Sensitive Privilege UseZAuditIPsecDriverzAudit IPsec DriverZAuditOtherSystemEventszAudit Other System EventsZAuditSecurityStateChangezAudit Security State ChangeZAuditSecuritySystemExtensionzAudit Security System ExtensionZAuditSystemIntegrityzAudit System IntegrityZSeTrustedCredManAccessPrivilegez-Access Credential Manager as a trusted caller�_sidConversion�_usernamesToSidObjects)rBrC�rights_assignmentrI�	LsaRightsrLZSeNetworkLogonRightz%Access this computer from the networkZSeTcbPrivilegez#Act as part of the operating systemZSeMachineAccountPrivilegezAdd workstations to domainZSeIncreaseQuotaPrivilegez"Adjust memory quotas for a processZSeInteractiveLogonRightzAllow log on locallyZSeRemoteInteractiveLogonRightz,Allow log on through Remote Desktop ServicesZSeBackupPrivilegezBackup files and directoriesZSeChangeNotifyPrivilegezBypass traverse checkingZSeSystemtimePrivilegezChange the system timeZSeTimeZonePrivilegezChange the time zoneZSeCreatePagefilePrivilegezCreate a pagefileZSeCreateTokenPrivilegezCreate a token objectZSeCreateGlobalPrivilegezCreate global objectsZSeCreatePermanentPrivilegezCreate permanent shared objectsZSeCreateSymbolicLinkPrivilegezCreate symbolic linksZSeDebugPrivilegezDebug programsZSeDenyNetworkLogonRightz-Deny access to this computer from the networkZSeDenyBatchLogonRightzDeny log on as a batch jobZSeDenyServiceLogonRightzDeny log on as a serviceZSeDenyInteractiveLogonRightzDeny log on locallyZ!SeDenyRemoteInteractiveLogonRightz+Deny log on through Remote Desktop ServicesZSeEnableDelegationPrivilegez>Enable computer and user accounts to be trusted for delegationZSeRemoteShutdownPrivilegez#Force shutdown from a remote systemZSeAuditPrivilegezGenerate security auditsZSeImpersonatePrivilegez)Impersonate a client after authenticationZSeIncreaseWorkingSetPrivilegezIncrease a process working setZSeIncreaseBasePriorityPrivilegezIncrease scheduling priority)rBr�rCrIr�rLZSeLoadDriverPrivilegezLoad and unload device driversZSeLockMemoryPrivilegezLock pages in memoryZSeBatchLogonRightzLog on as a batch jobZSeServiceLogonRightzLog on as a serviceZSeSecurityPrivilegez Manage auditing and security logZSeRelabelPrivilegezModify an object labelZSeSystemEnvironmentPrivilegez"Modify firmware environment valuesZSeManageVolumePrivilegez Perform volume maintenance tasksZSeProfileSingleProcessPrivilegezProfile single processZSeSystemProfilePrivilegezProfile system performanceZSeUndockPrivilegez$Remove computer from docking stationZSeAssignPrimaryTokenPrivilegezReplace a process level tokenZSeRestorePrivilegezRestore files and directoriesZSeShutdownPrivilegezShut down the systemZSeSyncAgentPrivilegez"Synchronize directory service dataZSeTakeOwnershipPrivilegez(Take ownership of files or other objectsZRecoveryConsoleSecurityLevelz6Recovery console: Allow automatic administrative logonzBSoftware\Microsoft\Windows NT\CurrentVersion\Setup\RecoveryConsoleZ
SecurityLevelZRecoveryConsoleSetCommandzLRecovery console: Allow floppy copy and access to all drives and all foldersZ
SetCommandZForceKeyProtectionzUSystem Cryptography: Force strong key protection for user keys stored on the computerz(Software\Policies\Microsoft\CryptographyZFIPSAlgorithmPolicyzWSystem Cryptography: Use FIPS compliant algorithms for encryption, hashing, and signingz8System\CurrentControlSet\Control\Lsa\FIPSAlgorithmPolicyZMachineAccessRestrictionzZDCOM: Machine Access Restrictions in Security Descriptor Definition Language (SDDL) syntaxz+Software\Policies\Microsoft\Windows NT\DCOMZMachineLaunchRestrictionzZDCOM: Machine Launch Restrictions in Security Descriptor Definition Language (SDDL) syntaxZUseMachineIdzFNetwork security: Allow Local System to use computer identity for NTLMZallownullsessionfallbackz9Network security: Allow LocalSystem NULL session fallbackz+SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0Z
AllowOnlineIDz`Network security: Allow PKU2U authentication requests to this computer to use online identities.z*SYSTEM\CurrentControlSet\Control\Lsa\pku2uZKrbSupportedEncryptionTypeszANetwork security: Configure encryption types allowed for KerberoszMSOFTWARE\Microsoft\Windows\CurrentVersion\policies\system\Kerberos\ParametersZSupportedEncryptionTypes�_dict_lookup_bitwise_addZNoLMHashzMNetwork security: Do not store LAN Manager hash value on next password changeZForceLogoffWhenHourExpirez6Network security: Force logoff when logon hours expireZLmCompatibilityLevelz2Network security: LAN Manager authentication levelZLDAPClientIntegrityz2Network security: LDAP client signing requirementsz&SYSTEM\CurrentControlSet\Services\ldapZNTLMMinClientSecz\Network security: Minimum session security for NTLM SSP based (including secure RPC) clientsz+System\CurrentControlSet\Control\Lsa\MSV1_0ZNTLMMinServerSecz\Network security: Minimum session security for NTLM SSP based (including secure RPC) serversZClientAllowedNTLMServerszUNetwork security: Restrict NTLM: Add remote server exceptions for NTLM authenticationZDCAllowedNTLMServerszENetwork security: Restrict NTLM: Add server exceptions in this domainZAuditReceivingNTLMTrafficz<Network security: Restrict NTLM: Audit Incoming NTLM Trafficz+SYSTEM\CurrentControlSet\Control\LSA\MSV1_0ZAuditNTLMInDomainzINetwork security: Restrict NTLM: Audit NTLM authentication in this domainZRestrictReceivingNTLMTrafficz6Network security: Restrict NTLM: Incoming NTLM trafficZRestrictNTLMInDomainzCNetwork security: Restrict NTLM: NTLM authentication in this domainZRestrictSendingNTLMTrafficzHNetwork security: Restrict NTLM: Outgoing NTLM traffic to remote serversZShutdownWithoutLogonz?Shutdown: Allow system to be shut down without having to log onZClearPageFileAtShutdownz'Shutdown: Clear virtual memory pagefilezBSystem\CurrentControlSet\Control\SESSION MANAGER\MEMORY MANAGEMENTZObCaseInsensitivezESystem objects: Require case insensitivity for non-Windows subsystemsz7System\CurrentControlSet\Control\SESSION MANAGER\KernelZProtectionModez_System objects: Strengthen default permissions of internal system objects (e.g. Symbolic Links)z0System\CurrentControlSet\Control\SESSION MANAGERz$System settings: Optional subsystemsz;System\CurrentControlSet\Control\SESSION MANAGER\SubSystemsZoptionalz_System settings: Use Certificate Rules on Windows Executables for Software Restriction Policiesz9SOFTWARE\Policies\Microsoft\Windows\safer\codeidentifiers�AuthenticodeEnabled)ZOptionalSubsystemsr�)rC�policieszUser Configuration)r=�User)2Zaudit_lookupZadvanced_audit_lookupZsc_removal_lookupZuac_admin_prompt_lookupZuac_user_prompt_lookupZenabled_one_disabled_zeroZ#enabled_one_disabled_zero_transformZs4u2self_optionsZaudit_transformZadvanced_audit_transformZ!enabled_one_disabled_zero_stringsZ+enabled_one_disabled_zero_strings_transformZsecurity_options_gpedit_pathZwindows_firewall_gpedit_pathZpassword_policy_gpedit_pathZaudit_policy_gpedit_pathZ!advanced_audit_policy_gpedit_pathZ"account_lockout_policy_gpedit_pathZ"user_rights_assignment_gpedit_pathZblock_ms_accountsZ&ldap_server_binding_token_requirementsZ ldap_server_signing_requirementsZ smb_server_name_hardening_levelsZlocked_session_user_infoZforce_guestZforce_key_protectionZfirewall_inbound_connectionsZfirewall_outbound_connectionsZfirewall_rule_mergingZ firewall_log_packets_connectionsZfirewall_notificationZfirewall_stateZkrb_encryption_typesZlm_compat_levelsZldap_signing_reqsZntlm_session_security_levelsZntlm_audit_settingsZntlm_domain_audit_settingsZincoming_ntlm_settingsZntlm_domain_auth_settingsZoutgoing_ntlm_settingsZ(enabled_one_disabled_zero_no_not_definedZ2enabled_one_disabled_zero_no_not_defined_transform�os�path�join�getenv�keys�chrr�)�self�r��I/opt/saltstack/salt/lib/python3.10/site-packages/salt/modules/win_lgpo.py�__init__as�\�	��	������
�

�

�����






�������������������
��
�������������)�����E����Y����m�������������&����4����C����S����b�
����v�����	�
������	����/�
�����B��������\��������v�����������������+���������F���������a���������|�������������������1����������K����������g���������������������!�����������>�����������[�����������x�����������������������3������������P���������]���������j���������w������������������������������������������<�������������Y�������������v���������������������������/��������������K�����������T��

�����������g������������t�����������}�����������������������������������������������(�
��������������B������������L������������[������������e������������o������������{�������������	��������������������������0�	������������C�
���������������]�	������������l�	������������~�	�������������
����������������0�
����������������M�	�������������_�	�������������q�	��������������	���������������	��������������)�	��������������<����������������P����������������c����������������t�	���������������	����������������
������������������4�	���������������C�	���������������U�	���������������g�	���������������y������������������
�������������������+�	����������������=�	����������������O�	����������������a�
�������������������~�������������������������������������	�����������������.�
�����������������@�
������������������T�	�����������������f�	�����������������z"�������������������
��������������������	������������������*�	���������������������C�	���������������������\�	������������������m�	�������������������	�������������������	�������������������$�	�������������������5���������������������F�	�������������������X��

��������������������k��������������������t�������������������������������������������"���������������������,���������������������6���������������������@���������������������J���������������������T���������������������^���������������������h���������������������
�����������������������������������������������������������������!
���������������������)
���������������������0
���������������������7
���������������������>����������������������G
���������������������N
���������������������V
���������������������]
���������������������d
���������������������k
���������������������r
���������������������y
��������������������������������������������
����������������������
����������������������
����������������������!
����������������������(
����������������������/
����������������������6
����������������������=
����������������������D
����������������������K
����������������������R
����������������������Y
����������������������`
����������������������g
����������������������o
����������������������v
����������������������}
����������������������
�����������������������
�����������������������
�����������������������
�����������������������!
�����������������������(
�����������������������/
�����������������������6
�����������������������=
�����������������������D
�����������������������K
�����������������������S
�����������������������Z
�����������������������a
�����������������������h������������������������q������������������������z
�����������������������
������������������������

������������������������
������������������������
������������������������ 
������������������������'
������������������������.
������������������������5
������������������������=
�������������������������H
�������������������������S
�������������������������^
�������������������������i
�������������������������t
�������������������������
�������������������������
��������������������������
��������������������������!
��������������������������,
��������������������������7
��������������������������B
��������������������������M
��������������������������X
��������������������������c
��������������������������n
��������������������������y
��������������������������
���������������������������
���������������������������
���������������������������&
���������������������������1
���������������������������?
���������������������������J
���������������������������U
���������������������������`
���������������������������k
���������������������������v
���������������������������
����������������������������

����������������������������
����������������������������#
����������������������������.
����������������������������9
����������������������������D
����������������������������O
����������������������������Z
����������������������������e
����������������������������p
����������������������������{
����������������������������
�����������������������������
�����������������������������
�����������������������������(�	����������������������������9�	����������������������������K��������������������������������e�����������������������������t�����������������������������������������������������������������������������������������"������������������������������0������������������������������?�
��������������������������������\������������������������������k������������������������������w�������������������������������������������������������������������&����������������������������������@����������������������������������Z��������������������������������k��������������������������������|���������������������������������������������������������������������1�����������������������������������J�����������������������������������d�����������������������������������~���������������������������������	���������������������������������	��������������������������������/���������������������������������A�
������������������������������������d�������������������������������z_policy_info.__init__cKs|rdSdS)z.
        ensures a value is not empty
        TFr���cls�val�kwargsr�r�r��	_notEmpty�sz_policy_info._notEmptycK�,|�dd�}|dur||krdS|dSdS)z6
        converts a number of seconds to days
        rqrN�Qr��get�r�r�r�rqr�r�r�rr��z_policy_info._seconds_to_dayscK�,|�dd�}|dur|dkr|S|dSdS)z6
        converts a number of days to seconds
        rqrNr�rr�r�r�r�r�rs�r�z_policy_info._days_to_secondscKr�)z9
        converts a number of seconds to minutes
        rqrN�<rr�r�r�r�r�r�r�z _policy_info._seconds_to_minutescKr�)z7
        converts number of minutes to seconds
        rqrNr�rr�r�r�r�r�r�r�z _policy_info._minutes_to_secondscKs|�dd�S)z-
        strips quotes from a string
        �"�)�replacer�r�r�r�ru"�z_policy_info._strip_quotescKsd|�d�S)z.
        add quotes around the string
        r�r�r�r�r�r�rv)r�z_policy_info._add_quotescKsTz|durt|�dkrWdSt|�dkrWdSd|��WSWdSty)YdSw)	z;
        converts a binary 0/1 to Disabled/Enabled
        Nrr#rr$zInvalid Value: r�
Invalid Value)�ord�	TypeErrorr�r�r�r�rx0s�z7_policy_info._binary_enable_zero_disable_one_conversioncKs8|dur|��dkrtd�S|��dkrtd�SdSdS)zZ
        converts Enabled/Disabled to unicode char to write to a REG_BINARY value
        NZDISABLEDrZENABLEDr)�upperr�r�r�r�r�ryBsz?_policy_info._binary_enable_zero_disable_one_reverse_conversioncKsT|dur(|dks|dks|dkrdS|dks|dkrdS|d	ks$|d
kr&dSdSdS)
z1
        converts 0/1/2 for dasd reg key
        Nrrr�ZAdministratorsrrzAdministrators and Power Usersrrz$Administrators and Interactive Usersrr�r�r�r�r�r{Qsz_policy_info._dasd_conversioncKsP|dur&|��dkrdS|��dkrdS|��dkrdS|��dkr$d	Sd
SdS)zA
        converts DASD String values to the reg_sz value
        NZADMINISTRATORSrzADMINISTRATORS AND POWER USERSrz$ADMINISTRATORS AND INTERACTIVE USERSrzNOT DEFINEDrzr�r�r�r�r�r�r�r|bsz%_policy_info._dasd_reverse_conversioncKs�|�dd�}|�dd�}|�dd�}t|t�r0|��dkrdSzt|�}Wn
ty/YdSw|d	urG||kr>|ksCn||krEdSdSdS)
z�
        checks that a value is in an inclusive range
        The value for 0 used by Max Password Age is actually 0xffffffff
        rjrrkrrq�not definedTFN)r��
isinstance�str�lower�int�
ValueError)r�r�r�ZminimumZmaximumrqr�r�r�rhxs 
�z _policy_info._in_range_inclusivecKsvt�d|�|dur9|�d�}t|�dkr7|ddkrdS|ddkr%d	S|dd
kr-dS|ddkr5dSd
SdSdS)z}
        converts the binary value in the registry for driver signing into the
        correct string representation
        z'we have %s for the driver signing valueN�,rrrzSilently SucceedrzWarn but allow installationrzDo not allow installationrr�)�log�trace�split�len)r�r�r�Z_valr�r�r�r~�s
z+_policy_info._driver_signing_reg_conversioncKsf|dur1|��dkrd�ddg�S|��dkr d�dtd�g�S|��dkr/d�dtd	�g�Sd
SdS)zm
        converts the string value seen in the GUI to the correct registry value
        for secedit
        NzSILENTLY SUCCEEDr�rrzWARN BUT ALLOW INSTALLATIONrzDO NOT ALLOW INSTALLATIONrr�r)r�r�r�r�r�r�r�r�sz3_policy_info._driver_signing_reg_reverse_conversionc	Ks�g}|D]9}zt�d|�}|dr|d�d|d��}n|d�}Wnty7t�|�}t�d|�Ynw|�|�q|S)zL
        converts a list of pysid objects to string representations
        r�r�\rzfUnable to convert SID '%s' to a friendly name. The SID will be displayed instead of a user/group name.)�
win32securityZLookupAccountSid�	ExceptionZConvertSidToStringSidr��warning�append)r�r�r�Z	usernamesZ_sidZuserSidr�r�r�r��s"
�
��z_policy_info._sidConversioncKs~|s|St|t�r|�d�}g}|D]*}zt�d|�d}|�|�Wqty<}z
t�d�t	d�
||���d}~ww|S)z=
        converts a list of usernames to sid objects
        r�r�rzHandle this explicitlyzEThere was an error obtaining the SID of user "{}". Error returned: {}N)r�r�r�r�ZLookupAccountNamer�r�r��	exceptionr�format)r�r�r��sids�_userZsid�er�r�r�r��s$


���z#_policy_info._usernamesToSidObjectscKs<t�d|�|dus|dkrdS|dkrdS|dkrdSd	S)
z|
        converts true/false/None to the GUI representation of the powershell
        startup/shutdown script order
        zscript order value = %sNr/rrF�$Run Windows PowerShell scripts firstrG�#Run Windows PowerShell scripts lastr�)r�r�r�r�r�r�rJ�sz0_policy_info._powershell_script_order_conversioncKs8|��d��kr
dS|��d��krdS|dkrdSdS)zc
        converts powershell script GUI strings representations to
        True/False/None
        r�rFr�rGrNr�r�r�r�r�r�rK�sz8_policy_info._powershell_script_order_reverse_conversioncKs�t�d|�|�dd�}d|vrJ|d��D]3\}}|r3t|���t|���kr2t�d|�|Sqt|���t|���krIt�d|�|SqdS)z�
        Retrieves the key or value from a dict based on the item
        kwarg lookup dict to search for item
        kwarg value_lookup bool to determine if item should be compared to keys
        or values
        z
item == %sr'Fr&zreturning key %szreturning value %sr�)r�r�r��itemsr�r�)r��itemr�r'�k�vr�r�r�r%s��z_policy_info._dict_lookupc	Ks�|�dd�}|�dd�}d}t|���dkrdS|r$t|t�s!dSd}n	t|t�s+dSg}d	|vrn|d	��D]4\}}|rOt|���d
d�|D�vrN||}q7d}|sY|dkrYd}|rkt|t�rk||@|krk|�|�q7|Sd
S)aY
        kwarg value_lookup bool to determine if item_list should be compared to keys
        or values

        kwarg test_zero is used to determine if 0 should be tested when value_lookup is false
        lookup should be a dict with integers for keys

        if value_lookup is True, item is expected to be a list
            the function will return the sum of the keys whose values are in the item list
        if value_lookup is False, item is expected to be an integer
            the function will return the values for the keys
            which successfully "bitwise and" with item
        r'F�	test_zeroNr�zInvalid Value: Not a listrzInvalid Value: Not an intr&cS�g|]}|���qSr��r���.0�zr�r�r��
<listcomp>A�z9_policy_info._dict_lookup_bitwise_add.<locals>.<listcomp>TzInvalid Value: No lookup passed)r�r�r�r��listr�r�r�)	r�r�r�r'r�Zret_valr�r�Zdo_testr�r�r�r�"s6

�
��z%_policy_info._dict_lookup_bitwise_addcKs6t|t�r|St|t�r|��dkrdS|�d�SdS)zU
        transform for setting REG_MULTI_SZ to properly handle "Not Defined"
        r�Nr�r�)r�r�r�r�r��r�r�r�r�r�r�rZNs


z(_policy_info._multi_string_put_transformcKst|t�r|S|dur
dSdS)zN
        transform for getting REG_MULTI_SZ to properly handle `None`
        Nrr�)r�r�r�r�r�r�r[]s

z(_policy_info._multi_string_get_transformcKs"t|t�r|��dkr
dS|SdS)zI
        transform for a REG_SZ to properly handle "Not Defined"
        r�N)r�r�r�r�r�r�r�rXis

�z"_policy_info._string_put_transformN)�__name__�
__module__�__qualname__�__doc__r��classmethodr�rrrsr�r�rurvrxryr{r|rhr~rr�r�rJrKr%r�rZr[rXr�r�r�r�r�s�3$
	


















+

rcCstjj��sdStsdStS)z'
    Only works on Windows systems
    )Fzwin_lgpo: Not a Windows System)Fz)win_lgpo: Required modules failed to load)�salt�utils�platformZ
is_windows�HAS_WINDOWS_MODULES�__virtualname__r�r�r�r��__virtual__us
r�cCs�d}|j�d�}|dkr|j|dd�}n|j}d|�d|��|_|��D]*}t|jt�rPd}|j�d�}|dkrD|j|dd�}n|j}d|�d|��|_q&|S)zI
    helper function to recursively update the namespaces of an item
    r��}rrN�{)�tag�find�getiteratorr�r�)r�Z
new_namespaceZ	temp_item�i�childr�r�r��_updateNamespace�s �r�cCs0|��D]}d|jvrd|jvr||jd<q|S)z�
    helper function to add the reg key to each policies element definitions if
    the key attribute is not defined to make xpath searching easier for each
    child in the policy <elements> item
    �	valueName�key)r��attrib)�policy_itemZregkeyr�r�r�r��_updatePolicyElements�s


�r�cC�ftjj�|d��}|��}Wd�n1swYtjdd|�d�dd�}tj	�
t�|��}|S)z�
    attempts to remove the "encoding='unicode'" from an xml file
    as lxml does not support that on a windows node currently

    see issue #38100 (Search.adml)

    For some reason this file is encoded 'utf-16'
    �rbNz encoding=[\'"]+unicode[\'"]+r��utf-16r��count�
r�r��files�fopen�read�re�sub�decode�lxmlr
�parse�io�StringIO�Zxml_file�fZxml_content�modified_xml�xml_treer�r�r��_remove_unicode_encoding��	
��rcCr�)z�
    Attempts to remove an invalid xmlns entry in newer versions of
    WindowsDefender.adml

    xmlns="http://schemas.microsoft.com/GroupPolicy/2006/07/PolicyDefinitions"

    For some reason this file is encoded 'utf-8'
    r�Nz xmlns=[\'"]+.*[\'"]+r��utf-8rr�r�r�r�r�r��_remove_invalid_xmlns�rrcCsN|�d�}|�d�}|�d�}|�d�}t�dd|�}|�|�d|�d|��S)	z%
    Escape spaces in xmlns urls
    rrrr!z\s+z%20z="r�)�groupr�r�)�matchZbefore_xmlnsZxmlns�urlZ	after_urlZencoded_urlr�r�r��_encode_xmlns_url�s



rcCs�tjjdd�}d}tjj�|d��}t�|�	��d@d�}Wd�n1s'wYt
j�t
j�
|��\}}|�d|�|��}t
j�td	d
d�}t
j�|�sVt
�|�t
j�||�}	t
j�|	��sMt�d||�t�t
j�||�d
|����}
|
D]}t
�|�q|tjj�|d��y}d}|�	�}
z|
�|�}
Wnty�t�d�d}|
�|�}
Ynw|
�d�D]H}d|vr�t�dt|�}d|vr�|�d�}||d��d�|}||dd��d�|d}|�|||�|||�� ��}d}||d7}q�Wd�n	1�s	wY|�dd��dd�}|�dd��dd�}|�dd��dd�}tjj�|	d��}|�!|�"|��Wd�n	1�sHwYztjj#|	|d�}W|Stjj$�y}zt%|	�}WY|Stjj$�y|t&|	�}YY|Sww) a1
    Parse the admx/adml file. There are 3 scenarios (so far) that we'll likely
    encounter:

    1. Valid File
    2. invalid encoding (encoding="unicode") which the lxml library doesn't
       recognize
    3. invalid xmlns entry in the xml header, which the lxml library doesn't
       recognize
    T)Zremove_commentsr�r�rp�XNr�cachedirr
Zpolicy_defsz/LGPO: Generating policy template cache for %s%s�*rzLGPO: Detecting encodingr��
zxmlns="z*(.*)(\bxmlns(?::\w+)?)\s*=\s*"([^"]+)"(.*)zkey="r�ru“u”u‘�'u’u–u—�wb)�parser)'r�r
Z	XMLParserr�r�r�r��zlib�crc32r�r�r��splitext�basenamer��__opts__�exists�makedirs�isfiler��debug�glob�remover��UnicodeDecodeErrorr�r�r�r�r�indexr�r��write�encoder��XMLSyntaxErrorrr)Zadm_filerr�ZrfhZ	file_hash�name�extZhashed_filenameZ	cache_dir�out_fileZ	file_listZ	file_path�encoding�raw�line�startZq1Zq2Z	found_keyZwfhr�r�r�r��
_parse_xml�sx�

��
 ���	����r&�c:\Windows\PolicyDefinitions�en-USc"
Cs�t}tj�d�}|�tj�d��|�tj�d��|�tj�d��tj�d�}t�d�}t�d�}t�d�}t�d	�}t�d
�}	tjj�	|�D�]�\}
}}|
|k�r�|D�]v}
t
j�|
�\}}|dkslt�
d|
�qVt
j�|
|
�}zt|�}Wntjjy�t�d
|�YqVw|��j}d}d|vr�|d|d<|�d�d}|jd�|�|d�d}|jd�|�|d�}|D]}|}t||�}||�d�|�q�|jd�|�|d�}|D]}|}t||�}d|jvr�t||jd�}||�d�|�q�|jd�|�|d�}|D]}|}t||�}||�d�|��qt
j�|
||d�}td|��s�t�d||
�t
j�|
|�d�d|d�}td|��s�t�d|dd�|
�t
j�|
||d�}td|��s�t�d||
�t
j�|
|�d�d|d�}td|��s�td �|||
���zt|�}Wntjj�y�t�d!|�YqVwd|v�r�|d|d<|�d�||�}|D]} | }!t|!|�}!|	|�d�|!��q�qVqI|td"<|td#<dS)$z�
    helper function to process all ADMX files in the specified policy_def_path
    and build a single XML doc that we can search/use for ADMX policy processing
    ZpolicyDefinitions�
categoriesr�ZpolicyNamespacesZpolicyDefinitionResourcesz/policyDefinitions/policiesz/policyDefinitions/categoriesz#/policyDefinitions/policyNamespacesz1//*[local-name() = "policyDefinitionResources"]/*z/policyDefinitionResourcesz.admxz%s is not an ADMX filezqAn error was found while processing admx file %s, all policies from this file will be unavailable via this moduler�Nr/zNone:z>/{0}policyDefinitions/{0}policyNamespaces/{0}target/@namespace��
namespacesrz//{0}policyDefinitions/{0}categories/{0}categoryz+/{0}policyDefinitions/{0}policies/{0}policyr�z./{0}policyDefinitions/{0}policyNamespaces/{0}*z.adml�file.file_existsz�An ADML file in the specified ADML language "%s" does not exist for the ADMX "%s", the the abbreviated language code will be tried.rzzAn ADML file in the specified ADML language code %s does not exist for the ADMX "%s", the fallback language will be tried.rz�An ADML file in the specified ADML fallback language "%s" does not exist for the ADMX "%s" the abbreviated fallback language code will be tried.zoAn ADML file in the specified ADML language "{}" and the fallback language "{}" do not exist for the ADMX "{}".zqAn error was found while processing adml file %s, all policies from this file will be unavailable via this module�lgpo.policy_definitions�lgpo.policy_resources)�INSTALL_LANGUAGEr�r
ZElementr��XPathr�r�r�Zos_walkr�rr�rr�r&r�errorZgetroot�nsmap�pop�xpathr�r�r�r��__salt__�infor�r�__context__)"r��languageZdisplay_language_fallbackZt_policy_definitionsZt_policy_definition_resourcesZpolicydefs_policies_xpathZpolicydefs_categories_xpathZpolicydefs_policyns_xpathZ$policydefs_resources_localname_xpathZpolicydef_resources_xpath�root�dirsr�Zt_admx_fileZadmx_file_nameZ
admx_file_extZ	admx_filer�r+Znamespace_stringZthis_namespacer)�categoryZtemp_catr��policyZtemp_polZpolicy_namespacesZ	policy_nsZtemp_nsZ	adml_fileZpolicydefs_resourcesZpolicydefs_resourceZt_poldefr�r�r��_load_policy_definitions(s


�


��

�����
���


���
��
�
��
�����


���r=cC�&dtvrt�d�t||d�tdS)Nr-z LGPO: Loading policy definitions�r�r8�r7r�rr=r?r�r�r��_get_policy_definitions��
rAcCs@dtvrt�d�t�d�dtvrt�d�t�d�dSdS)z�
    Clears the policy definitions and resource stored in ``__context__``. They
    will be rebuilt the next time a policy is applied.

    CLI Example:

    .. code-block:: bash

        salt '*' lgpo.clear_policy_cache
    r-z(LGPO: Removing cached policy definitionsr.z&LGPO: Removing cached policy resourcesN)r7r�rr3r�r�r�r��clear_policy_cache�s


�rCcCr>)Nr.zLGPO: Loading policy resourcesr?r@r?r�r�r��_get_policy_resources�rBrDcCs&i}|D]}|jd||jd<q|S)z3
    build a namespace map for an ADMX element
    �	namespace�prefix)r�)Zusing_elementsZthisMapr�r�r�r��_buildElementNsmap�srGcCs�dtvr[t�d�td�}t�|�}d|ji}|D]<}d|d<|d|d<|dd	kr1d
|d<n|ddkr<d|d<n|dd
krGd|d<n	d�|d�|d<|||d<q|td<|rctd|StdS)a
    Loads audit.csv defaults into a dict in __context__ called
    'lgpo.audit_defaults'. The dictionary includes fieldnames and all
    configurable policies as keys. The values are used to create/modify the
    ``audit.csv`` file. The first entry is `fieldnames` used to create the
    header for the csv file. The rest of the entries are the audit policy names.
    Sample data follows:

    {
        'fieldnames': ['Machine Name',
                       'Policy Target',
                       'Subcategory',
                       'Subcategory GUID',
                       'Inclusion Setting',
                       'Exclusion Setting',
                       'Setting Value'],
        'Audit Sensitive Privilege Use': {'Auditpol Name': 'Sensitive Privilege Use',
                                          'Exclusion Setting': '',
                                          'Inclusion Setting': 'No Auditing',
                                          'Machine Name': 'WIN-8FGT3E045SE',
                                          'Policy Target': 'System',
                                          'Setting Value': '0',
                                          'Subcategory': u'Audit Sensitive Privilege Use',
                                          'Subcategory GUID': '{0CCE9228-69AE-11D9-BED3-505054503030}'},
        'Audit Special Logon': {'Auditpol Name': 'Special Logon',
                                'Exclusion Setting': '',
                                'Inclusion Setting': 'No Auditing',
                                'Machine Name': 'WIN-8FGT3E045SE',
                                'Policy Target': 'System',
                                'Setting Value': '0',
                                'Subcategory': u'Audit Special Logon',
                                'Subcategory GUID': '{0CCE921B-69AE-11D9-BED3-505054503030}'},
        'Audit System Integrity': {'Auditpol Name': 'System Integrity',
                                   'Exclusion Setting': '',
                                   'Inclusion Setting': 'No Auditing',
                                   'Machine Name': 'WIN-8FGT3E045SE',
                                   'Policy Target': 'System',
                                   'Setting Value': '0',
                                   'Subcategory': u'Audit System Integrity',
                                   'Subcategory GUID': '{0CCE9212-69AE-11D9-BED3-505054503030}'},
        ...
    }

    .. note::
        `Auditpol Name` designates the value to use when setting the value with
        the auditpol command

    Args:
        option (str): The item from the dictionary to return. If ``None`` the
            entire dictionary is returned. Default is ``None``

    Returns:
        dict: If ``None`` or one of the audit settings is passed
        list: If ``fieldnames`` is passed
    zlgpo.audit_defaultsz*Loading auditpol defaults into __context__zauditpol.get_auditpol_dump�
fieldnamesr��Machine Name�Subcategory�
Auditpol NamezCentral Policy Stagingr�zPlug and Play Eventsr�zToken Right Adjusted Eventsr�zAudit {})r7r�r�	__utils__�csv�
DictReaderrHr�)�option�dump�readerZaudit_defaults�rowr�r�r��_get_advaudit_defaults�s(8






rSc
Cs�tj�dd�}tj�|ddd�}tj�|dddd	d
dd�}td|�sHtd|�r2td
||�dStd�}td|�td|d�|��dSdS)a�
    This function checks for the existence of the `audit.csv` file here:
    `C:\Windows\security\audit`

    If the file does not exist, then it copies the `audit.csv` file from the
    Group Policy location:
    `C:\Windows\System32\GroupPolicy\Machine\Microsoft\Windows NT\Audit`

    If there is no `audit.csv` in either location, then a default `audit.csv`
    file is created.
    �
SystemRoot�
C:\Windows�security�audit�	audit.csvr;r<r=�	Microsoft�
Windows NT�Auditr,�	file.copyrH�
file.makedirsz
file.writer�N)r��environr�r�r�r5rS)�system_root�f_audit�f_audit_gpo�field_namesr�r�r��_advaudit_check_csvQs&��rccCs�dtvs|durOtj�dd�}tj�|ddd�}t�i}tjj	j
|dd	��}t�|�}|D]
}|�
|d
|di�q.Wd�n1sFwY|td<td�|d�S)
a�
    Get the Advanced Auditing policy as configured in
    ``C:\Windows\Security\Audit\audit.csv``

    Args:

        option (str):
            The name of the setting as it appears in audit.csv

        refresh (bool):
            Refresh secedit data stored in __context__. This is needed for
            testing where the state is setting the value, but the module that
            is checking the value has its own __context__.

    Returns:
        bool: ``True`` if successful, otherwise ``False``
    �lgpo.adv_audit_dataTrTrUrVrWrX�r��moderJ�
Setting ValueN)r7r�r^r�r�r�rcr�r�r�r�rMrN�update)rO�refreshr_r`Zaudit_settings�csv_filerQrRr�r�r��_get_advaudit_valuevs
��rlcCs:tj�dd�}tj�|ddd�}tj�|dddd	d
dd�}tjdd
ddd�}dddddd�}t�z�tj	j
j|dd���}t�
|�}tj	j
j|jdd��v}	tj|	|jd�}
|
��d
}|D]1}|d|kr�|dks|||d<||d<t�d||�|
�|�nt�d|�d}q\|
�|�q\|s�|dks�t�d||�t|�}
|
�|
d|
d |
d|
d!|||
d"|d#��d}Wd$�n1s�wYWd$�n1s�wY|�rtd%|j|dd&�td'|�td%|j|dd&�W|��td(|j�|SW|��td(|j�|S|��td(|j�w))a�
    Helper function that sets the Advanced Audit settings in the two .csv files
    on Windows. Those files are located at:
    C:\Windows\Security\Audit\audit.csv
    C:\Windows\System32\GroupPolicy\Machine\Microsoft\Windows NT\Audit\audit.csv

    Args:
        option (str): The name of the option to set
        value (str): The value to set. ['None', '0', '1', '2', '3']

    Returns:
        bool: ``True`` if successful, otherwise ``False``
    rTrUrVrWrXr;r<r=rYrZr[�wFz.csv)rg�delete�suffixrFrrrr�r/rrrrrerf)rHrJr/�Inclusion SettingrhzLGPO: Setting %s to %szLGPO: Removing %sTrI�
Policy Target�Subcategory GUID�Exclusion Setting)rIrrrJrsrqrtrhNr\)Zremove_existingr]�file.remove)r�r^r�r�r��tempfileZNamedTemporaryFilercr�r�r�r�rMrNrZ
DictWriterrHZwriteheaderr�r�ZwriterowrSr5�close)rO�valuer_r`raZf_temp�auditpol_valuesrkrQZtmp_file�writerZ
value_writtenrR�defaultsr�r�r��_set_advaudit_file_data�s��
��	
������5��r|cCs0dddddd�}t|�}td|d||d�S)	a�
    Helper function that updates the current applied settings to match what has
    just been set in the audit.csv files. We're doing it this way instead of
    running `gpupdate`

    Args:
        option (str): The name of the option to set
        value (str): The value to set. ['None', '0', '1', '2', '3']

    Returns:
        bool: ``True`` if successful, otherwise ``False``
    rrrrrpzauditpol.set_settingrK)rrx)rSrL)rOrxryr{r�r�r��_set_advaudit_pol_data
s��r}cCs�t||d�s
td|����t||d�st�d|�dtvr!t|�|dur4t�d|�td�|�dSt�d||�|td|<dS)	a]
    Helper function to update the Advanced Audit policy on the machine. This
    function modifies the two ``audit.csv`` files in the following locations:

    C:\Windows\Security\Audit\audit.csv
    C:\Windows\System32\GroupPolicy\Machine\Microsoft\Windows NT\Audit\audit.csv

    Then it applies those settings using ``auditpol``

    After that, it updates ``__context__`` with the new setting

    Args:
        option (str): The name of the option to set
        value (str): The value to set. ['None', '0', '1', '2', '3']

    Returns:
        bool: ``True`` if successful, otherwise ``False``
    �rOrxz Failed to set audit.csv option: zLFailed to apply audit setting: %s
Policy will take effect on next GPO updaterdNz&LGPO: Removing Advanced Audit data: %sz*LGPO: Updating Advanced Audit data: %s: %sT)	r|rr}r�r1r7rlrr3r~r�r�r��_set_advaudit_value$s ��rcCstdtvritd<|tdvr&t�d|�tjjj|dd�}td�||i�t�dtd||�td||S)N�lgpo.netsh_dataz'LGPO: Loading netsh data for %s profiler
)�profile�storezLGPO: netsh returning value: %s)	r7r�rr�r��win_lgpo_netshZget_all_settingsrir�)r�rOrdr�r�r��_get_netsh_valueSs��r�cCs|dvrtd|����t�d||||�|dkr/tjjj||dkr#|nd|dkr*|nddd�|d	kr>tjjj|||dd
�|dkrLtjjj||dd�|d
krp|dvrZ|dkrZd}|�	d�re|dd�}tjjj
|||dd
�|tdvr�t�d|�td�|i�dS)N)rardrer]zLGPO: Invalid section: zHLGPO: Setting the following
Profile: %s
Section: %s
Option: %s
Value: %srarbrcr
)r�ZinboundZoutboundr�rd)r��settingrxr�r])r�r]r�re)rfrgr0r1ZLogrr�z(LGPO: Clearing netsh data for %s profileT)
r�r�r�r�r�r�Zset_firewall_settingsZset_settingsZ	set_state�
startswithZset_logging_settingsr7r3�r��sectionrOrxr�r�r��_set_netsh_valuedsF���
�r�cCs�tj�tddt�d��}z7tdddd|g�tjjj	|dd	��}|�
�}Wd
�n1s0wY|Wtd|�rDtd|�SStd|�rRtd|�ww)
z�
    Helper function that loads secedit data. It runs `secedit /export /cfg
    <file_name>` which creates a file that contains the secedit data.

    Returns:
        str: The contents of the file generated by the secedit command
    r	�secedit-z.txtzcmd.run�seceditz/export�/cfgr��r"Nr,ru)r�r�r�r�UUIDr5r�r�r�r��	readlines)Zf_exp�fp�secedit_datar�r�r��_load_secedit_data�s
���r�cCs,dtvs|durt�d�t�td<tdS)a�
    Helper function that returns the secedit data in __context__ if it exists
    and puts the secedit data in __context__ if it does not.

    Args:

        refresh (bool):
            Refresh secedit data stored in __context__. This is needed for
            testing where the state is setting the value, but the module that
            is checking the value has its own __context__.

    Returns:
        str: secedit data from __context__
    �lgpo.secedit_dataTzLGPO: Loading secedit data)r7r�rr�)rjr�r�r��_get_secedit_data�s

r�cCs4t�}|D]}|�|�r|�d�d��SqdS)zN
    Helper function that looks for the passed option in the secedit data
    �=rr)r�r�r��strip)rOr��_liner�r�r��_get_secedit_value�s
�r�cCsXtj�t�d�ddd�}tj�tddt�d��}z�tjjj	|dd	d
��
}|�
|�Wd�n1s4wYdd
d|d|g}td|�}|dksat�
d�Wtd|�r_td|�dSdSddd|g}td|�}|dks�t�
d�Wtd|�r�td|�dSdSt�dd�Wtd|�r�td|�dSdStd|�r�td|�ww)z?
    Helper function to write secedit data to the database
    r:rVZdatabasezsalt.sdbr	r�z.infrmr�r�Nr�z/importz/dbr�zcmd.retcoderz&Secedit failed to import template datar,ruFz
/configurez)Secedit failed to apply security databaser�T)r�r�r�r�rr�r�r�r�r�rr5r�rr7r3)Zinf_dataZf_sdbZf_infr��cmd�retcoder�r�r��_write_secedit_data�s:�
��
����r�cCsxi}d|vr0||dvr.t�}|d|dvr|d|d}t||d|�|fi|��S|Sd|vr:|dkr:dS|S)z�
    helper function to transform the policy value into something that more
    closely matches how the policy is displayed in the gpedit GUI
    rLrmrr r)r�getattr)rxr<�transform_typeZt_kwargs�_policydatar�r�r��_transform_value�s ��r�cCs�t�d||�d|vrA|dr?t|dt�r ||dvrdSdSt|dt�r?t�}t||dd�|fi|dd��s?dSdSdS)a�
    helper function to validate specified value is appropriate for the policy
    if the 'Settings' key is a list, the value will check that it is in the list
    if the 'Settings' key is a dict we will try to execute the function name
        from the 'Function' key, passing the value and additional arguments from
        the 'Args' dict
    if the 'Settings' key is None, we won't do any validation and just return
        True
    if the Policy has 'Children', we'll validate their settings too
    zvalidating %s for policy %srIFrlrmT)r�rr�r��dictrr�)rxr<r�r�r�r��_validateSetting�s"
��
��r�c
Cs`z|rt�dtj�}|g}t�|||�}WdSty/}z
t�d|�WYd}~dSd}~ww)z;
    helper function to add an account right to a user
    NTz7Error attempting to add account right, exception was %sF)r��
LsaOpenPolicy�POLICY_ALL_ACCESSZLsaAddAccountRightsr�r�r��Z	sidObject�
user_rightZ
_polHandleZuser_rights_list�_retr�r�r�r��_addAccountRightss����r�c
Cs\zt�dtj�}|g}t�||d|�}WdSty-}zt�d�WYd}~dSd}~ww)z@
    helper function to remove an account right from a user
    NFTz(Error attempting to delete account right)r�r�r�ZLsaRemoveAccountRightsr�r�r�r�r�r�r��_delAccountRights+s�
��r�cCs"g}t�dtj�}t�||�}|S)zI
    helper function to return all the user rights assignments/users
    N)r�r�r�Z!LsaEnumerateAccountsWithUserRight)r�r�Z	polHandler�r�r��_getRightsAssignments;sr�cCsh|�d�r2|�d�r2t�dd|�}|�d�}|d}|d}t|||d�}|r2|D]}|j��Sd	S)
a/
    helper function to take the 'displayName' attribute of an element and find
    the value from the ADML data

    adml_xml_data :: XML data of all ADML files to search
    display_name :: the value of the displayName attribute from the ADMX entry
                    to search the ADML data for
    z$(�)z(^\$\(|\)$)r��.rr)ZdisplayNameTypeZ
displayNameIdN)r��endswithr�r�r��ADML_DISPLAY_NAME_XPATH�textr�)�
adml_xml_data�display_nameZdisplayname_typeZdisplayname_id�search_results�resultr�r�r��_getAdmlDisplayNameEs	
�r�c
Cs|�d|�d��}d}|r�|D]}}t�|j�j}|jdurRt|�}|rR|d}t|�rR|D]}||kr5nt�|j�jdkrJt|d�rJt|d��	�}q-|�
d�rRd}|dvrp|�d	�}|D]}	|	jrn|	j�	��	d
�Sq]q|dvr�|jr�|j�	��	d
���S|�	d
���SqdS)zP
    helper function to check for a presentation label for a policy element
    z"//*[@*[local-name() = "refId"] = "z"]r�Nrr�r�)ZtextBoxZcomboBoxz.//*[local-name() = "label"]�:)ZdecimalTextBoxZlongDecimalTextBoxZdropdownListZlistBoxZcheckBoxr�ZmultiTextBox)r4r
�QNamer��	localnamer��PRESENTATION_ANCESTOR_XPATH�TEXT_ELEMENT_XPATHr��rstripr�r�)
�	adml_dataZref_idr�Zalternate_labelr�Z
the_localnameZpresentation_elementZp_itemZlabel_itemsZ
label_itemr�r�r��_getAdmlPresentationRefIdas@

�

��	�
r�cCs�|t|vrt||St|d�}|r+d|jvr+t||jd�}|r*|t||<|}n|rDd|jvrDt||jd�}|rD|t||<|}|�d���}|S)zD
    helper function to retrieve the full policy name if needed
    �r8�displayName�idr�)�adm_policy_name_maprDr�r�r�r�)r��policy_name�return_full_policy_names�
adml_languager�ZfullPolicyNamer�r�r��_getFullPolicyName�s$

��r�c
Cs�d}g}d�d�}|r
i}|r�t�}t|�|��dkr+|jt|�|�d�d��}nd}t�|�}t�	||tj
�}dd�|D�}|r�|D]�}	||	��|�d	�d�|	�
����|d
�}
t|
�dkrn|
d�d��td��}t|
�d
kr�|�|
d
d��}|dks�|dkr�|r�|dkr�t�d|�D]}|}q�n1|dkr�t�d|�D]}|}q�n!d}n|dkr�|�d��td���td��}n
|�d��td��}|r�t�d�|||<qEt|�dkr�t�d�|�|�qE|r�|}|S)z�
    helper function to do a search of Policy data from a registry.pol file
    returns the "data" field
    https://msdn.microsoft.com/en-us/library/aa374407(VS.85).aspx
    [key;value;type;size;data]
    N�;�	utf-16-lerr�	utf-32-lecSsg|]}|�qSr�r�)r��mr�r�r�r��sz*_getDataFromRegPolData.<locals>.<listcomp>�]r!rrr"rR�	REG_QWORD�I�QrYz!we want value names and the valuez/we have multiple matches, we will return a list)rrr�r�Z
vtype_reverser�r�r��escape�finditer�
IGNORECASEr%r�endr�r�r��struct�unpackr�r�r�)
�
search_string�policy_data�return_value_namerx�values�encoded_semicolon�registry�vtype�matchesrZ	pol_entryr�r�r�r�r��_getDataFromRegPolData�sh
�
����� 



�r�c	Csd}t�|�}g}||�D]u}	d}
d}|	D]Y}|d}d|jvr&|jd}
n|}
d|jvr3|jd}nt�dt�|	�j|j|j�n,||�D]&}t||
|||�}|rhtt	�
|�|�rg|
d}
t�d|
||�qG|�|�qGq|r�|dkr�||
kr�t�d|�d	Sq
|r�d
S|S)a�
    helper function to process an enabled/disabled/true/falseList set

    if test_items is True, it will determine if the policy is enabled or
    disabled returning True if all items are configured in the registry.pol file
    and false if they are not

    if test_items is False, the expected strings for the items will be returned
    as a list

    returns True if the enabled/disabledList is 100% configured in the
    registry.pol file, otherwise returns False
    zt.//*[local-name() = "decimal" or local-name() = "delete" or local-name() = "longDecimal" or local-name() = "string"]rrr�r�zX%s item with attributes %s in policy %s does not have the required "valueName" attributezcfound the search string in the pol file,%s of %s items for policy %s are configured in registry.polz%s all items are setTF)
r
r0r�r�r1r�r��_processValueItemrr�r�r�r�)�policy_elementr��
policy_key�xpath_object�policy_file_data�
test_itemsZxpath_stringZvalue_item_child_xpathZexpected_stringsZlist_elementZconfigured_itemsZrequired_itemsr��item_keyZitem_valuename�
value_itemr�r�r�r��_checkListItem�sZ�



�
���	��r�c
Csd||�D]+}|D]&}	t|	|||||d�}
|s|
Stt�|
�|�r.t�d|�dSqqdS)aR
    helper function to process the parent of a value item object
    if test_item is True, it will determine if the policy is enabled/disabled
    returns True if the value is configured in the registry.pol file, otherwise returns False

    if test_item is False, the expected search string will be returned

    value type parents:
        boolean: https://msdn.microsoft.com/en-us/library/dn606009(v=vs.85).aspx
        enabledValue: https://msdn.microsoft.com/en-us/library/dn606006(v=vs.85).aspx
        disabledValue: https://msdn.microsoft.com/en-us/library/dn606001(v=vs.85).aspx

    ��
check_deletedz9found the search string in the pol file, %s is configuredTF)r�rr�r�r�r�)r�r�r��policy_valueNamer�r�r��	test_item�elementr�r�r�r�r��_checkValueItemParent<s*����r�cCsTtd��d�}|dur
|St|t�s tdt|��dt|�����d�|�d�|g�S)Nrr�zValue z is not a string type
Type: �)r�rr�r�r��repr�typer�)rx�encoded_nullr�r�r��_encode_stringhs
�r�c
CsVt�}d}d�d�}td��d�}|r|�d�}|r|�d�}|rE|sE|dkr0t�dt|��}n|dkr=t�dt|��}n|d	krEt|�}|r�d	}d
�d�d�|||d�d�|||t|j|��d
�|tt	dtd����d����d
�|d�d�|d�d�g�}	|	Sd
�d�d�||||||t|j|��d
�|tt	|���d
�||d�d�g
�}	|	S)zs
    helper function similar to _processValueItem to build a search string for a
    known key/value/type/data
    Nr�r�rrRr�r�r�rWr��[�**del.r�� r�)
rrr�r��packr�r�r�r�r�)
�reg_key�
reg_valueName�	reg_vtype�reg_datar�r��this_element_valuer�r��expected_stringr�r�r��_buildKnownDataSearchStringtsj


 ��%���r�cs�t�}d}d}	d�d�}
td��d�}|r|�d�}|r!|�d�}t���jdkrZt�|�jdkrZd}	d	�jvrEt�d
t	�jd	��}�nt
�dt�|�jt���j|j�j�dSt���jdkr�t�|�jdkr�d
}	d	�jvr~t�dt	�jd	��}�n�t
�dt�|�jt���j|j�j�dSt���jdkr�d}	t�j
�}�n�t�|�jdk�r\d}t���jdkr�|dur�d}|s�d}	t�dd�}d}�n4t���jdk�rd}	|}
|dur�t�d
t	|��}d�jvr��jd��dkr�d}	|
dur�t|
��d�}|�rd}	�n�t���jdk�r@d
}	|}
|du�r t�dt	|��}d�jv�r>�jd��dk�r>d}	|
du�r>t|
��d�}�n�t���jdk�rhd}	d�jv�r]�jd��dk�r]d}	|du�rft|�}�n�t���jdk�r�|�svdnd}	|du�r�d�td��|�td��}�nst���jdk�r�d}d}g}|}|du�r�dd �tdt|�d�D�}d!�jv�r��jd!��d"k�r�d�d#�d�|||
d$�d�||
t|j|	��d%�|
ttd&td����d����d%�|
d&�d�|d'�d�g�}d�jv�r�d}	�j�d(d"���dk�r"|du�r!d)d �|��D�}d*d �|��D�}n)d+�jv�r?�jd+d,k�r>|du�r>�fd-d �|D�}n|du�rKd.d �|D�}|�s�|du�r�t
�d/|�|}t
�d0||�t|�D]B\}}|d�d#�d�|||
||�d�||
t|j|	��d%�|
tt||�td����d����d%�|
t||�d'�d�g
�}�qfnU|d�d#�d�|||
g�}nFd�d#�d�|||
d$�d�||
t|j|	��d%�|
ttd&td����d����d%�|
d&�d�|d'�d�g�}nt���jd1k�r�|du�r�	|�r\|�s\|du�rCt|t��rt
�d2|�|�d%�}d�d#�d�|||
|||
t|j|	��d%�|
tt|���d%�|
|d'�d�g
�}nd�d#�d�|||
|||
t|j|	��d%�|
g	�}|�s�t���jd3k�sk|�r�d�d#�d�|||
d4�d�|||
t|j|	��d%�|
ttd&td����d����d%�|
d&�d�|d'�d�g�}|Sd�d#�d�|||
|||
t|j|	��d%�|
tt|���d%�|
|d'�d�g
�}|S)5ac
    helper function to process a value type item and generate the expected
    string in the Registry.pol file

    element - the element to process
    reg_key - the registry key associated with the element (some inherit from
              their parent policy)
    reg_valuename - the registry valueName associated with the element (some
                    inherit from their parent policy)
    policy - the parent policy element
    parent_element - the parent element (primarily passed in to differentiate
                     children of "elements" objects
    check_deleted - if the returned expected string should be for a deleted
                    value
    this_element_value - a specific value to place into the expected string
                         returned for "elements" children whose values are
                         specified by the user
    NrWr�r�r�decimal�elementsrRrxr�z�The %s child %s element for the policy with attributes: %s does not have the required "value" attribute. The element attributes are: %s�longDecimalr�r��stringT�booleanF�IrZstoreAsTextrFr�Z
expandableZ
REG_EXPAND_SZ�	multiTextrYz	{0}{1}{1}r�r�cS�g|]}t|��qSr��r�r�r�r�r�r�:s�z%_processValueItem.<locals>.<listcomp>ZadditiverGr�z
**delvals.r�r�r��
explicitValuecSrr�r�r�r�r�r�r�r�Yr�cSrr�r)r�r�r�r�r�r�Zr��valuePrefixr�csg|]}d��jd|��qS)z{}{}r)r�r�r�r�r�r�r�as��cSrr�rr�r�r�r�r�hr�z5_processValueItem has an explicit element_value of %sz1element_valuenames == %s and element_values == %s�enumzConverting %s to bytesrnr�)rrr�r
r�r�r�r�r�r�r�r1r�r�r�r�r�r��ranger�r�r�r�r�r��	enumerater�r)r�r��
reg_valuenamer<�parent_elementr�r�r�r�Z
this_vtyper�r�Z standard_element_expected_stringZ
requested_valZdel_keysZelement_valuenamesZelement_valuesr�r�r�rr�r��s





�	


�	
�

�
�
��
����
�

��

�����
�
����	 ��


���� ��%���r�c7Cs.t�d|�tt|d�}g}i}i}i}	t|d�}
t|d�}|�r@t�d|�t�tj	j
�dtd��d��dt�tj	j
�d	td����dt�t�
t�d
��d|����d�d
��}t�dt|��t��}
|D]N}|�td��d
��d
��d�d
���}|r�t|
|d�}t�dt|�|�|D]$}t�|�jdkr�||vr�|�|�q�t|�D]}||vr�|�|�q�q�qit�dt��|
�|�rFt�d�t��}
t|
|d�}|D]}||vr�|�|�q�|D]W}|j|j}||vr�i||<d|||jd<|�r||	v�r	i|	|<t ||jd||d�|	||jd<t�d|jd�||v�r-i||<t!|||d�|||jd<q�t�dt��|
�t�dt|��t��}
|D�]�}d}d}d}d}d|jv�rk|jd}n
t�"d|j��n�d |jv�r�|jd }d|jv�r�|jd}n
t�"d!|j��n�|j|j}t#|��r�|dk�r�t$|��s�t%|��r�d}d}t&||||t#|��r�d"}t�d#|�||v�r�i||<||||<t%|��r|dk�rt'|��s�t#|��r�d}d}t&||||t%|��rd$}t�d%|�||v�ri||<||||<t'|��rF|dk�rFt$|��s"t%|��r&d}d}t(|||t'|��rFd"}t�d&|�||v�r@i||<||||<t$|��r~|dk�r~t'|��sZt#|��r^d}d}t(|||t$|��r~d$}t�d'|�||v�rxi||<||||<|�s�|�r�t)t�
t*||d(d)��|��r�d"}t�d*|�||v�r�i||<||||<n't)t�
t*||d(ddd+��|��r�d$}t�d,|�||v�r�i||<||||<t+|��r�|�s�|d"k�r�i}i}d}t+|�D�]�} | D�]z}!t |!|!jd-||d�}"d||"<|!j�,d|�}#|!j�,d |�}$t�|!�jd.k�r�t|!�dk�r�t-|!��r>|"|v�r>t&|!||#|$t-|��r>d||"<t�d/|!jd-�t.|!��rc|"|v�rct&|!||#|$t.|��rcd||"<|d0}t�d1|!jd-�t/|!��r�|"|v�r�t�d2�t(|!||t/|��r�d||"<t�d/|!jd-�t0|!��r�|"|v�r�t�d3�t(|!||t0|��r�d||"<|d0}t�d1|!jd-��q�t)t�
t1|!|#|$|| dd+��|��r�d||"<|d0}t�d1|!jd-��q�t)t�
t1|!|#|$|| dd+��|��r�d||"<t�d/|!jd-��q�t�|!�jd4k�st�|!�jd5k�st�|!�jd6k�st�|!�jd7k�rmt)t�
t1|!|#|$|| dd+��|��r?d$||"<|d0}t�d8|!jd-��q�t)t�
t1|!|#|$|| dd+��|��rkt2t1|!|#|$|| dd+�|�}%|%||"<t�d9|!jd-|%��q�t�|!�jd:k�r�t)t�
t1|!|#|$|| dd+��|��r�t�d;|!jd-�d$||"<|d0}�q�|!D]B}&t&|&|!jd-|#|$t3|��r�t4|&��r�t�d<�t(|&||#t4|��r�t�d=�t5||&jd>�||"<n�q�t5||&jd>�||"<n�q��q�t�|!�jd?k�rgd}'d@|!jv�r|!jd@��dAk�rt�dB�d}'gdC�}(dD�6|(�})tj	j
�|)�})t)t�
t1|!|#|$|| dd+��|)|��rEt2t1|!|#|$|| dd+�||'dE�}%|%||"<t�dF|!jd-|%��q�t)t�
t1|!|#|$|| dd+��|��rgd$||"<|d0}t�d8|!jd-��q�q�|�r�t|�7��dk�r�t|�7��t|�7��k�r�|t|�7��k�r�t�dG|�||v�r�i||<d$|||<n*||v�r�i||<||||<t�dH|�n|d"k�r�||v�r�i||<||||<|�r||v�r|||v�r||	v�r�i|	|<t ||jd||d�|	||<||||v�r|	||}*|||�8|�}+|+||||*<||v�r4|||v�r4||v�r)i||<t!|||d�|||<�qTt�dIt��|
�|�r�|�r�|�s�t�9dJ�t��}
i},i}-t:|�D]�}.t:||.�D]Y}|	|.|||.v�r�||.|}/|/�;�|/�|	|.|�||.�8|�|dK�6|/�<d|-|	|.|<�qb||.�8|�||.|	|.|<|.|,v�r�i|,|.<||,|.|	|.|<�qb|.|,v�r�|,|.D](}0||.|,|.|0}/|/�;�|/�|0�t�dL|/�||.�8|0�|dK�6|/�<�qŐqZt�dMt��|
�t:|�D]}.||.ik�r|�8|.��q�|�r�|�r�|�r�t�9dN�t��}
|D]^}.||.D]E}1|1||.v�rli}2d}3||.|1D]'}4i}5|3�r[|1}6|�rM|	|.|1}6|6||.�8|1�i|5|4<d}3n|2|5|4<|5}2�q;|2�rlt<�=||2�}�q(|.|v�r||.ik�r|�8|.��q"t�dMt��|
�t|dOdP|ii}|S)Qa
    rewrite of _getAllAdminTemplateSettingsFromRegPolFile where instead of
    looking only at the contents of the file, we're going to loop through every
    policy and look in the registry.pol file to determine if it is
    enabled/disabled/not configured
    zPOLICY CLASS == %s�policy_pathr�zPOLICY CLASS %s has file dataz\]r�$r�z^\[r�z][zSearching %s policies...r�)ZkeyvaluezFound %s policies for %sr<zSearch complete: %s secondsz!Gathering non configured policies)�registry_classrr�r�r�r�r�z-building hierarchy for non-configured item %s��policy_definitionr�r�zGathering complete: %s secondszExamining %s policies...NTFr��9policy item %s does not have the required "key" attributer�z:policy item %s does not have the required "name" attributer$�-%s is enabled by detected ENABLED_VALUE_XPATHr#�/%s is disabled by detected DISABLED_VALUE_XPATH�,%s is enabled by detected ENABLED_LIST_XPATH�.%s is disabled by detected DISABLED_LIST_XPATHrRr�9%s is enabled by no explicit enable/disable list or valuer��:%s is disabled by no explicit enable/disable list or valuer�r��element %s is configured truer�element %s is configured false�checking trueList�checking falseListr�r�r�r�element %s is disabled�"element %s is enabled, value == %sr�enum element %s is disabled�enum item has a valueList�!all valueList items exist in filer�r�rrF�.explicitValue list, we will return value names�z(?!\*�\*�Dr��l�V�ar&�s�\.r��)r�� element %s is enabled values: %s�#%s is disabled by all enum elements�%s is enabled by enum elementsz Examination complete: %s seconds�$Compiling non hierarchical return...r��full_path_list == %sz Compilation complete: %s seconds� Compiling hierarchical return...rC�Administrative Templates)>r�r�rrrArDr�r�r�r��stringutils�to_bytesr�r�rrr�r��timer�r��REGKEY_XPATHr
r�r�r��POLICY_ANCESTOR_XPATH�ALL_CLASS_POLICY_XPATHrr2rFr�r��_build_parent_listr1�ENABLED_VALUE_XPATH�DISABLED_LIST_XPATH�DISABLED_VALUE_XPATHr��ENABLED_LIST_XPATHr�rr��ELEMENTS_XPATHr��TRUE_VALUE_XPATH�FALSE_VALUE_XPATH�TRUE_LIST_XPATH�FALSE_LIST_XPATHr�r��VALUE_XPATH�VALUE_LIST_XPATHr�r�r�r3rr��reverse�
dictupdateri)7�policy_classr�r��hierarchical_return�return_not_configuredr�Z
admx_policies�policy_vals�	hierarchy�
full_names�admx_policy_definitions�adml_policy_resourcesZpolicy_filedata_splitZ
start_timer�Zpolicy_item_keyZ
admx_itemsZ	admx_itemZnot_configured_policiesZnot_configured_policyZnot_configured_policy_namespace�admx_policy�this_valuename�this_policy_setting�element_only_enabled_disabled�%explicit_enable_disable_value_setting�this_keyZthis_policynameZthis_policynamespace�required_elements�configured_elements�policy_disabled_elements�
elements_item�
child_item�this_element_name�	child_key�child_valuename�configured_value�	enum_itemr��	regex_str�
delvals_regex�	full_namer��
unpathed_dict�pathed_dict�policy_namespace�full_path_list�path_needed�hierarchy_item�tdict�
first_itemr��newdict�
h_policy_namer�r�r��_checkAllAdmxPolicies�s�


����
��
�
���
�
����
����
���
�
��
���
���
��
���
���
���
��
������
����	��
��

���
�	���
�	����

����

�������
�
����
�
����
�
����
�
�������
�
���

�����������$��

���
����
����
�
������Y�
���
��
����

���

�
��
��

��

����
�
�
�

�
���
�
�
���

�
��rlc	Cs�g}tt|j��}|j|�d�|jd�}t|d�}|r?|d}d�|�}t|j||jd��}t�||j�}t	||||||d�}|S)z[
    helper function to build a list containing parent elements of the ADMX
    policy
    �:parentCategory/@refr*r�rz(/policyDefinitions/policyNamespaces/{}:*�r�rd�parent_category�policy_nsmapr�r�)
�next�iterr2r4rAr�rGrFri�_admx_policy_parent_walk)	rr�r�Zparent_listrdrorMZnsmap_xpathZthis_namespace_mapr�r�r�r9s:�
�����r9cCs�t|d�}d}d}|�d�dkr0|�d�d}|�d�d}|�|�}t�|t|j||d���}|�||�}|j||d�rt|j||d�d}	t|	|	j	d||d	�}
|�
|
�|	j|�d
�|d�rtt|||	j|�d
�|d�d|||d�}|S)zo
    helper function to recursively walk up the ADMX namespaces and build the
    hierarchy for the policy
    r�z5/policyDefinitions/categories/{}:category[@name="{}"]z,/policyDefinitions/policyNamespaces/{}:usingr�rrr*rrrmrn)rAr�r�r�rFrirGr4r�r�r�rs)r�rdrorpr�r�rMZcategory_xpath_stringZusing_xpath_stringZtparent_categoryZthis_parent_namer�r�r�rs>s`

�������

����rscCs�|rEgd�}d�|�}tjj�|�}d�tjj�d�t�|�d|t�|�d��dg�}t�||tj	�}|rE||�
�|�d|���d	�Sd
S)z�
    helper function to do a search of Policy data from a registry.pol file
    for a policy_regpath and policy_regkey combo
    )z(\*r$r%r�r&r*z|\*r$r%r�r&r'r(r&r)r*z){0,1}r+r�z\[s;��;�]rN)
r�r�r�r3r4r�r��lstrip�searchr�r%rr�)r�Zpolicy_regpathZ
policy_regkeyr_�specialValueRegexZ_thisSearchrr�r�r��_regexSearchKeyValueCombozs&
��
�rzcCs�|sd}tjj�d�}|D]D}|�d�d�d�}tj|d|�d�dtjd�}t	�
d|�t|||�}|rDt	�
d	||�|�||�}q
t	�
d
|�d�
||g�}q
|S)z�
    helper function to take a list of strings for registry.pol file data and
    update existing strings or append the strings
    r��(\*\*Del\.|\*\*DelVals\.){0,1}rur�[r��flags�item value name is %s�replacing %s with %s�appending %s�r�r�r3r4r�rwr�r�r�r�r�rzr�r�)Zstring_listr�ry�this_stringZ
list_item_keyZlist_item_value_name�data_to_replacer�r�r��_policyFileReplaceOrAppendList�s(���r�cCs�|sd}tjj�d�}d}|s4|�d�d�d�}tj|d|�d�dtjd�}t	�
d	|�t|||�}|rEt	�
d
||�|�||�}|St	�
d|�d�
||g�}|S)z�
    helper function to take a ADMX policy string for registry.pol file data and
    update existing string or append the string to the data
    r�r{Nrurr|rr}rr�r�r�)r�r��append_onlyryr�r�Zitem_value_namer�r�r��_policyFileReplaceOrAppend�s,����r�r=cCs�d}d}t|d�}t|d�}t||dddd�}|D]@}||D]9}	t|||	���dkr@|�|i��|	d�dur?t�d|	�qt�d	|	�||vrNi||<|||	|||	<qq|D�]�}||D�]�}
t�d
|
�d}d}d}
t|||
���dk�r�t�d|
�|j	|�
|
�d
|id�}|�r�|d}d|jv�r�|jd|ks�|jddk�r�d|jvr�|jd}n
t�d|j��ngd|jvr�|jd}
t
|�r�d}t||
||
t
dddd�}t||�}t|�r�d}t||
|tddd�}t�d|
�t||�}|�s|
�rt||
dddd�}t||�}t|��r�t�d|
�t|�D]�}|D]�}|}|
}d|jv�r6|jd}d|jv�rA|jd}t�|�jdk�ryt|��sTt|��ryttd�}|D]}t||
|||ddd�}t�d|
|�t||�}�q[�q%t�|�jdk�s�t�|�jdk�s�t�|�jd k�s�t�|�jd!k�s�t�|�jd"k�s�t�|�jd#k�r�t|||||dd�}t�d$|�t||�}�q%t�|�jd%k�r�t|||||dd�}t�d$|�t||�}�q%�q!qct�d&|
|�qct�d'|j�qct�d(|
�|j	|�
|
�d
|id�}t�d)|�|�r(|d}d|jv�r(|jd|k�s.|jddk�r(d|jv�r:|jd}n
t�d|j��n�d|jv�rO|jd}
t|��rgd}t||
||
tdddd�}t||�}t|��r�d}t||
|tddd�}t�d*|
�t||�}|�s�|
�r�t||
dd+dd�}t||�}t|��r(t|�D�]�}|D�]}|}|
}d|jv�r�|jd}d|jv�r�|jd}|jd,|||
v�r$t�|�jdk�rt|��s�t|��rg}|||
|jd,�rt||
|tddd�}t�d-|
�n
t||
|tddd�}t||�}�q�t�|�jdk�rRt|��s$t|��rRd.}|||
|jd,�r?t||
||tdddd�}nt||
||tdddd�}t||�}�q�t�|�jdk�st�|�jdk�st�|�jd k�st�|�jd!k�st�|�jd"k�r�t|||||d|||
|jd,d/�}t�d0|�t||�}�q�t�|�jd#k�r�|D]L}|||
|jd,t||jd1�� �k�r�t||jd,||t!dddd�}t||�}t"|��r�t||
|t"ddd�}t�d2|jd,�t||�}n�q��q�t�|�jd%k�r$t|||||d|||
|jd,d/�}t�d0|�t||dd3�}�q��q�qcq\zt#|t$|d4t$|d5t$|d6d7�WdSt%�y[}z
t�&d8|�WYd}~dSd}~ww)9a�
    helper function to prep/write adm template data to the Registry.pol file

    each file begins with REGFILE_SIGNATURE (u'\u5250\u6765') and
    REGISTRY_FILE_VERSION (u'\x01\00')

    https://msdn.microsoft.com/en-us/library/aa374407(VS.85).aspx
    +    https://msdn.microsoft.com/en-us/library/cc232696.aspx
    [Registry Path<NULL>;Reg Value<NULL>;Reg Type;SizeInBytes;Data<NULL>]
    r�z%//ns1:*[@id = "{0}" or @name = "{0}"]r�F�rGr�r�rHrI�not configuredNzPolicy "%s" removedz!adding %s to base_policy_settingszworking on admPolicy %s�disabledztime to disable %sZns1r*r�classZBothr�rr�T)r�r�)r�z'working with disabledList portion of %srRr�zchecking elements of %sr�)ZtrueListZ	falseListzworking with %s portion of %sr�r�r�rrz"I have disabled value string of %sr�zGpolicy %s was found but it does not appear to be valid for the class %sz;policy item %s does not have the required "class" attributez&time to enable and set the policy "%s"zfound this_policy == %sz&working with enabledList portion of %srr�z#working with trueList portion of %sr�)r�r�z!I have enabled value string of %sr�z$working with valueList portion of %s)r�rZgpt_extension_location�gpt_extension_guid)Z
data_to_writeZpolicy_file_pathZ
gpt_extensionr�z^Unhandled exception occurred while attempting to write Adm Template Policy File.
Exception: %s)'rArDrlr�r�r�r3r�r�r4r�r�r1r<r�r�r;r�r�r�r>r
r�r�rArBr�r:r=r?r@r�r�rCrDr	rrr�)Zadmtemplate_datar�rZ
existing_dataZpolicySearchXpathrMrNZbase_policy_settingsZ
adm_namespaceZ
adm_policyZ	admPolicyrSrTrPZthis_policyZdisabled_value_stringZdisabled_list_stringsrXrYr[r\�	temp_dictZ	this_listZenabled_value_stringZenabled_list_stringsZlist_stringsZvalue_stringr^�excr�r�r��_writeAdminTemplateRegPolFile�s


�������
��
�

�
��������

�����	������
�
�
�
�
�
����������Y�����

�
�
�������


������������	������������
��
�
�
�
�
��������
�������
��
��
��
����
4������������Y


�����r�c
Csjd}tj�|dd�r�tjj�|ddd��}|��}Wd�n1s'wY|r�zt|�	d��
d��}t�d|�Wnt
yX}zt�d|d	�t|��d}~wwd
|dvr�|dd
��dd�|��D�vr�d
|dvr�t�d|dd
�|dd
��dd�||dd
��D�vr�||dd
|dd
��SdS||dd
SdSdS)a
    helper function to parse/read a GPO Startup/Shutdown script file

    psscript.ini and script.ini file definitions are here
        https://msdn.microsoft.com/en-us/library/ff842529.aspx
        https://msdn.microsoft.com/en-us/library/dd303238.aspx
    NrDrAr�r�uzHave deserialized data %sz7An error occurred attempting to deserialize data for %srBr@cSr�r�r�r�r�r�r�r� r�z1_getScriptSettingsFromIniFile.<locals>.<listcomp>rHzNeed to look for %scSr�r�r�r�r�r�r�r� s��)r�r�rr�r�r�r�r�rr�rwr�r�r�r�rr�r�)Zpolicy_infoZ
_existingDataZfhrr1r�r�r��_getScriptSettingsFromIniFile�sR
��������
���r�cCsttj�t�d�ddddd�}tj�t�d�ddddd�}tj�t�d�ddddd�}tj�t�d�ddddd�}d	S)
a�
    helper function to write local GPO startup/shutdown script

    scripts are stored in scripts.ini and psscripts.ini files in
    ``WINDIR\System32\GroupPolicy\Machine|User\Scripts``

    these files have the hidden attribute set

    files have following format:
        empty line
        [Startup]
        0CmdLine=<path to script 0>
        0Parameters=<script 0 parameters>
        [Shutdown]
        0CmdLine=<path to shutdown script 0>
        0Parameters=<shutdown script 0 parameters>

    Number is incremented for each script added

    psscript file also has the option of a [ScriptsConfig] section, which has
    the following two parameters:
        StartExecutePSFirst
        EndExecutePSFirst

    these can be set to True/False to denote if the powershell startup/shutdown
    scripts execute first (True) or last (False), if the value isn't set, then
    it is 'Not Configured' in the GUI
    r:r;r<r=r>r?rEr�N)r�r�r�r�)ZpsscriptZ_machineScriptPolicyPathZ"_machinePowershellScriptPolicyPathZ_userScriptPolicyPathZ_userPowershellScriptPolicyPathr�r�r��_writeGpoScript- s6����r�cCs�g}t|d�}t|d�}t|||d�}|r�t|�dkrU|d}t||jdd|d�}|�|�|�|jd�t|d|d�}	|	��|	�|�|�d	�	|	��d||d
fSg}|D]!}t||jdd|d�}t|d|d�}	|	�|�|�d	�	|	��qYd�	|�}
d�
||
�}d
d
g|fSt||d�}g}
|}|s�t�
d|�d	|vr�|�d	�}
|
��}t||d�}|�r�d
}d}g}t|�dk�r�t�d|�d}|D]�}t|dd���|ks�|�|�q�|
�rlt�d|
�d�
|j�d�d|jd�}d�
|j||�}g}|j||jd�}|�st�d|�|�|�|D]E}t�d|�t|d|d�}|��|
|k�rIt�d|
|�t|�dk�rGt�d�|�|��qt�d|
|�t�d|�|�|��qt|�dk�rk|�|d�q�d�
|j�d�d|jd�}t|||d�}|�s�|�|�q�|D]
}||v�r�|�|��q�t|�dk�r�|�r�d
}|D�]}t�d |j|j�d�
|j�d�d|jd�}t�d!|�|�s�t�d"||�t|||d�}|�r�t�d#|�t�d$|�t|�dk�s�|
�r�|�s�d
}|D]}d
}|
�rt|d|d�}|��t�d%|
|�|
|k�rd}nd}|�ryt�d&||�d|jv�rht||jdd|d�}|�|�|�|jd�t|d|d�}	|	��|	�|�|�d	�	|	��d||d
fSd'}|�
|�}d
d
g|fS�q�|�s�d(�
|�}d
d
g|fS�q�|D]'}t|d|d�}|��|�|�|�r�d)�	|d	�	|�g�}�q�d	�	|�}�q��q�|�r�d*}d
d
g|�
||�fSd
d
gd+|�d,|��fS)-zD
    (success_flag, policy_xml_item, policy_name_list, message)
    r�)r�rrrrTrrr�Nz
 - z^ADMX policy name/id "{}" is used in multiple ADMX files.
Try one of the following names:
 - {}F)r�zTrying another: %sr�z7multiple ADML entries found matching the policy name %sr�zwe have hierarchy of %sz$({}.{})r�r�zH//{}:policy[@displayName = "{}" and (@class = "Both" or @class = "{}") ]r*z;No admx was found for the adml entry %s, it will be removedzpolicy_name == %sz7hierarchy %s does not match this item's hierarchy of %szYonly 1 admx was found and it does not match this adml, it is safe to remove from the listz+hierarchy %s matches item's hierarchy of %sz!search_result %s added to results)r�rz1found an ADML entry matching the string! %s -- %szsearching for displayName == %szGsearch for an admx entry matching display_name %s and registry_class %sz$processing admx_search_results of %szmultiple_adml_entries is %sztesting %s == %sz8found the ADMX policy matching the display name %s -- %szMADMX policy with the display name {} does nothave the required name attributez$Unable to correlate {} to any policy�, z�ADML policy name "{}" is used as the display name for multiple policies. These policies matched: {}. You can utilize these long names to specify the correct policyzUnable to find z policy )rArD�ADMX_SEARCH_XPATHr�r�r�r�r9rEr�r��ADML_SEARCH_XPATHr�r�r�r3r�r�r�r�rFr4r2�ADMX_DISPLAYNAME_SEARCH_XPATHr)r�rGr��policy_aliasesrMrNZadmx_search_results�
the_policyZpolicy_display_namerer��msgZadml_search_resultsrKZhierarchy_policy_nameZmultiple_adml_entriesZsuggested_policiesZadml_to_removeZadml_search_resultZdisplay_name_searchvalZpolicy_search_stringZadmx_resultsZthese_admx_search_resultsZ
search_resultZthis_hierarchyZadml�foundZpossible_policyZthis_parent_listr�r�r��_lookup_admin_templateg s�

��
�
��

��
��������
�
��
������
�

�
�������
���
�
�
� ���
����r�cCs:||gddgdd�}|��}t�}||jvr&d�|j�}d�||�|d<|S||j|dvrX|d�|j|d|d	�d
|d<d|d<d
|j|d|vrVd
|d<|S|j|dD]3}|j|d|d	}||kr�|d�|�d
|d<d|d<d
|j|d|vr�d
|d<|Sq_|j|dD]7}|j|d|d	}|��|��kr�|d�|�d
|d<d|d<d
|j|d|vr�d
|d<|Sq�t|||d�\}}	}
}|�rt|	�D]$}|D]}
t	|
|
j
dd
|d�}|d�|
j
d|
j
d|gd��q�q�|
|d<d
|d<d|d<|S||d<|S)a
    Returns information about a specified policy

    Args:
        policy_name (str):
            The name of the policy to lookup
        policy_class (str):
            The class of policy, i.e. machine, user, both
        adml_language (str):
            The ADML language to use for Administrative Template data lookup

    Returns:
        dict: Information about the specified policy

    CLI Example:

    .. code-block:: bash

        salt '*' lgpo.get_policy_info 'Maximum password age' machine

    You can use ``lgpo.get_policy_info`` to get all the possible names that
    could be used in a state file or from the command line (along with elements
    that need to be set/etc). The key is to match the text you see in the
    ``gpedit.msc`` gui exactly, including quotes around words or phrases. The
    "full path" style is really only needed when there are multiple policies
    that use the same base name. For example, ``Access data sources across
    domains`` exists in ~10 different paths. If you put that through
    ``get_policy_info`` you'll get back a message that it is used for multiple
    policies and you need to be more specific.

    CLI Example:

    .. code-block:: bash

        salt-call --local lgpo.get_policy_info ShellRemoveOrderPrints_2 machine

        local:
            ----------
            message:
            policy_aliases:
                - Turn off the "Order Prints" picture task
                - ShellRemoveOrderPrints_2
                - System\Internet Communication Management\Internet Communication settings\Turn off the "Order Prints" picture task
            policy_class:
                machine
            policy_elements:
            policy_found:
                True
            policy_name:
                ShellRemoveOrderPrints_2
            rights_assignment:
                False

    Escaping can get tricky in cmd/Powershell. The following is an example of
    escaping in Powershell using backquotes:

    .. code-block:: bash

        PS>salt-call --local lgpo.get_policy_info "Turn off the `\`"Order Prints`\`" picture task" machine

        local:
            ----------
            message:
            policy_aliases:
                - Turn off the "Order Prints" picture task
                - ShellRemoveOrderPrints_2
                - System\Internet Communication Management\Internet Communication settings\Turn off the "Order Prints" picture task
            policy_class:
                machine
            policy_elements:
            policy_found:
                True
            policy_name:
                Turn off the "Order Prints" picture task
            rights_assignment:
                False

    This function can then be used to get the options available for specifying
    Group Policy Objects to be used in state files. Based on the above any of
    these *should* be usable:

    .. code-block:: bash

        internet_communications_settings:
          lgpo.set:
            - computer_policy:
                Turn off the "Order Prints" picture task: Enabled

    .. code-block:: bash

        internet_communications_settings:
          lgpo.set:
            - computer_policy:
                ShellRemoveOrderPrints_2: Enabled

    When using the full path, it might be a good idea to use single quotes
    around the path:

    .. code-block:: bash

        internet_communications_settings:
          lgpo.set:
            - computer_policy:
                'System\Internet Communication Management\Internet Communication settings\Turn off the "Order Prints" picture task': 'Enabled'

    If you struggle to find the policy from ``get_policy_info`` using the name
    as you see in ``gpedit.msc``, the names such as "ShellRemoveOrderPrints_2"
    come from the ``.admx`` files. If you know nothing about ``.admx/.adml``
    relationships (ADML holds what you see in the GUI, ADMX holds the more
    technical details), then this may be a little bit too much info, but here is
    an example with the above policy using Powershell:


    .. code-block:: bash

        PS>Get-ChildItem -Path C:\Windows\PolicyDefinitions -Recurse -Filter *.adml | Select-String "Order Prints"

        C:\windows\PolicyDefinitions\en-US\ICM.adml:152:      <string id="ShellRemoveOrderPrints">Turn off the "Order Prints" picture task</string>
        C:\windows\PolicyDefinitions\en-US\ICM.adml:153:      <string id="ShellRemoveOrderPrints_Help">This policy setting specifies whether the "Order Prints Online" task is available from Picture Tasks in Windows folders.
        C:\windows\PolicyDefinitions\en-US\ICM.adml:155:The Order Prints Online Wizard is used to download a list of providers and allow users to order prints online.
        C:\windows\PolicyDefinitions\en-US\ICM.adml:157:If you enable this policy setting, the task "Order Prints Online" is removed from Picture Tasks in File Explorer folders.

    From this grep, we can see id "ShellRemoveOrderPrints" is the ID of the
    string used to describe this policy, then we search for it in the ADMX:

    .. code-block:: bash

        PS>Get-ChildItem -Path C:\Windows\PolicyDefinitions -Recurse -Filter *.admx | Select-String "ShellRemoveOrderPrints"

        C:\windows\PolicyDefinitions\ICM.admx:661:    <policy name="ShellRemoveOrderPrints_1" class="User" displayName="$(string.ShellRemoveOrderPrints)" explainText="$(string.ShellRemoveOrderPrints_Help)" key="Software\Microsoft\Windows\CurrentVersion\Policies\Explorer" valueName="NoOnlinePrintsWizard">
        C:\windows\PolicyDefinitions\ICM.admx:671:    <policy name="ShellRemoveOrderPrints_2" class="Machine" displayName="$(string.ShellRemoveOrderPrints)" explainText="$(string.ShellRemoveOrderPrints_Help)" key="Software\Microsoft\Windows\CurrentVersion\Policies\Explorer" valueName="NoOnlinePrintsWizard">

    Now we have two to pick from. And if you notice the ``class="Machine"`` and
    ``class="User"`` (which details if it is a computer policy or user policy
    respectively) the ``ShellRemoveOrderPrints_2`` is the "short name" we could
    use to pass through ``get_policy_info`` to see what the module itself is
    expecting.
    Fzpolicy not found)r�rGr��policy_foundr��policy_elements�messager��MThe requested policy class "{}" is invalid, policy_class should be one of: {}r�r�r�rBTr�r�r�r��r�rGr�r�rr�)Z
element_idZelement_aliases)�titlerr�r�r�r�r�r�r>r�r�)r�rGr��retr��policy_classes�pol�_p�successZpolicy_xml_item�policy_name_listr�rXrYrZr�r�r��get_policy_info|!s��	
���������
r�cCsRi}t�}|dus|��dkr|j��}n!|��dd�|jD�vr1d}t|�|d�|j������|��g}|D]�}|j|d}	i}
|	D]�}d}||j|dvr\|j|d|}nP|j|dD]}
|j|d|
d}||kr|j|d|
}|
}qc|dur�|j|dD] }
|j|d|
d}|��|��kr�|j|d|
}|
}q�|r�|}t|�|
|<|r�|
�	|�|
|d<|d}|r�d	|vr�d
}i}t
|d	�D]}i}|r�||
�	|�i||<d}n|||<|}q�|r�t�|
|�}
qEt
d�|���t�|
t|||||d
��}
|j|d	|
v�r |j|d	|
i}|}
t�||
�}q8|S)aY
    Get a policy value

    Args:

        policy_class (str):
            Some policies are both user and computer, by default all policies
            will be pulled, but this can be used to retrieve only a specific
            policy class User/USER/user = retrieve user policies
            Machine/MACHINE/machine/Computer/COMPUTER/computer = retrieve
            machine/computer policies

        return_full_policy_names (bool):
            True/False to return the policy name as it is seen in the
            ``gpedit.msc`` GUI or to only return the policy key/id.

        hierarchical_return (bool):
            True/False to return the policy data in the hierarchy as seen in the
            ``gpedit.msc`` GUI. The default of False will return data split only
            into User/Computer configuration sections

        adml_language (str):
            The ADML language to use for processing display/descriptive names
            and enumeration values of ADMX template data, defaults to en-US

        return_not_configured (bool):
            Include Administrative Template policies that are 'Not Configured'
            in the return data

    Returns:
        dict: A dictionary containing the policy values for the specified class

    CLI Example:

    .. code-block:: bash

        salt '*' lgpo.get machine return_full_policy_names=True
    NZbothcSr�r�r�r�r�r�r�r��"r�zget.<locals>.<listcomp>z_The policy_class {} is not an available policy class, please use one of the following: {}, Bothr�r�rBrCTFzSThe specified policy {} is not currently available to be configured via this moduler�)rr�r�r�rr�r�r��_get_policy_info_settingr3�reversedrFrirrl)rGr�rHr�rI�valsr�r��p_classZthis_class_policy_namesZ
class_valsr��_polr<r�Z
vals_key_nameZ	firstItemrh�levelrjr�r�r�r�r�U"s�.��
��
�����
r�cCs�d|vr$td|dd|dd|dd�d}t�d||d�n�d	|vr;t|d	d
d�}t�d||d�n�d
|vrWt|d
d|d
d
d�}t�d||d�nfd|vrnt|dd
d�}t�d||d�nOd|vr�t�d|dd�}||dd
}t�d||d�n/d|vr�t|dd
�}t�d||d�nd|vr�t	|�}t�d||d�nt
d�|���t||dd�}|S)a
    Some policies are defined in this module and others by the ADMX/ADML files
    on the machine. This function loads the current values for policies defined
    in this module.

    Args:
        policy_definition (dict):
            A sub-dict of Policies property of the _policy_info() class.
            Basically a dictionary that defines the policy

    Returns:
        The transformed value. The transform is defined in the policy
        definition. It can be a list, a string, a dictionary, depending on how
        it's defined

    Usage:
        policy_data = _policy_info()
        policy_name = 'RemoteRegistryExactPaths'
        policy_definition = policy_data.policies['Machine']['policies'][policy_name]
        policy_value = _get_policy_info_setting(policy_definition)
    r�reg.read_valuerSrTrU�vdataz$Value %r found for Regisry policy %srBrPrO)rOz$Value %r found for Secedit policy %sr`r_)r�rOz"Value %r found for NetSH policy %sr�z%Value %r found for AuditPol policy %sroNrnz)Value %r found for NetUserModal policy %sr�z&Value %r found for LSARights policy %srDz&Value %r found for ScriptIni policy %sz4Unknown or missing mechanism in policy_definition
{}r(�rxr<r�)
rLr�r�r�r�rl�win32net�NetUserModalsGetr�r�rr�r�)rrxZmodal_returnr�r�r�r��"st


��
�
�

�
�
���
�
����r�c,
Cs�|j�dd�}|j�dd�}|dus|durtd�|j���|j�dd�}d}|j|j}	d}
d}tt|d	�}t|d
�}
i}t	|�rn|dkrnt
|�sPt|�rnd}
d}t||||t	|d�rnt
�d|�d
}||�|	i�|<t|�r�|dkr�t|�s~t	|�r�d}
d}t||||t|d�r�t
�d|�d}||�|	i�|<t|�r�t
|�s�t|�r�d}
d}t|||t|d�r�t
�d|�d
}||�|	i�|<t
|�r�t|�s�t	|�r�d}
d}t|||t
|d�r�t
�d|�d}||�|	i�|<|�s4|�r4tt�t||ddd��|��rt
�d|�d
}||�|	i�|<n tt�t||dddd��|��r4t
�d|�d}||�|	i�|<i}i}t|��r"|
�sE|d
k�ri}i}d}t|�D�]q}|D�]j}t||jd||d�}d||<|j�d|�}|j�d|�}t�|�jdk�rbt|�dk�rt|��r�||v�r�t||||t|d��r�d||<t
�d|jd�t|��r�||v�r�t||||t|d��r�d||<|d}t
�d|jd�t|��r�||v�r�t
�d �t|||t|d��r�d||<t
�d|jd�t|��r||v�rt
�d!�t|||t|d��rd||<|d}t
�d|jd��qTtt�t |||||dd"��|��rBd||<|d}t
�d|jd��qTtt�t |||||dd"��|��r`d||<t
�d|jd��qTt�|�jd#v�r�tt�t |||||dd"��|��r�d||<|d}t
�d$|jd��qTtt�t |||||dd"��|d%��r�t!t |||||dd"�|d%�}|||<t
�d&|jd|��qTt�|�jd'k�r7tt�t |||||dd"��|��r�t
�d(|jd�d||<|d}�qT|D]F}t||jd||t"|d��r3t#|��r&t
�d)�t|||t#|d��r$t
�d*�t$|
|jd+d,�||<n�q�t$|
|jd+d,�||<n�q�qTt�|�jd-k�r�d}d.|jv�rY|jd.�%�d/k�rYt
�d0�d}gd1�}d2�&|�}t'j(j)�*|�}tt�t |||||dd"��||d%��r�t!t |||||dd"�||d3�}|||<t
�d4|jd|��qTtt�t |||||dd"��|��r�d||<|d}t
�d$|jd��qT�qO|
�rdt|�+��k�r�t|�+��k�rnn'|t|�+��k�r�t
�d5|�d|�|	i�|<n7t
�d6|�||�|	i�|<n(||�|	i�|<n|d
k�r||�|	i�|<n||�|	i�|<n||�|	i�|<|�rn|	|v�rn|||	v�rn|�|	i�t||jd||d�||	|<|||	|v�rn||	|}||	|�,|�}|||	||<|	|v�r�|||	v�r�t-|||d7�|�|	i�|<|�r|�r|�st
�.d8�i} i}!t/|�D]�}"t/||"�D]H}#||"|#}|||"v�r�||"|#}$|$�0�|$�1||"|#�||"�,|#�|d9�&|$�<d|!|<�q�||"�,|#�||"|<|#| �|"i�|<�q�| �|"i�D](}%||"| |"|%}$|$�0�|$�1|%�t
�d:|$�||"�,|%�|d9�&|$�<�q�q�t/|�D]-}"||"ik�r3|�,|"��q#t2||"t3��rO|	|"k�rO|�sO|�4||"�|�,|"��q#|�r�|�r�|�r�t
�.d;�|D]^}"||"D]E}&|&||"v�r�i}'d}(||"|&D]'})i}*|(�r�|&}+|�r�||"|&}+|+||"�,|&�i|*|)<d}(n|'|*|)<|*}'�qz|'�r�t5�4||'�}�qg|"|v�r�||"ik�r�|�,|"��qat|d<d=|ii}|S)>a�
    Get the current setting for polices set via the policy templates (ADMX/ADML)
    files

    Args:
        admx_policy (obj):
            The XPath object as returned by the ``_lookup_admin_template``
            function

        policy_class (str):
            The policy class. Must be one of ``machine`` or ``user``

        adml_language (str):
            The language code for the adml file to use for localization. The
            default is ``en-US``

        return_full_policy_names (bool):
            Returns the full policy name regardless of what was passed in
            ``policy_name``

        hierarchical_return (bool):
            Returns a hierarchical view of the policy showing its parents

    Returns:
        dict: A dictionary containing the policy settings

    Usage:
        policy_name = 'AutoUpdateCfg'
        policy_class = 'machine'
        adml_language = 'en-US'
        success, policy_obj, _, _ = _lookup_admin_template(
            policy_name=policy_name,
            policy_class=policy_class,
            adml_language=adml_language)
        if success:
            setting = _get_policy_adm_setting(
                admx_policy=policy_obj,
                policy_class=policy_class,
                adml_language=adml_language,
                return_full_policy_names=return_full_policy_names,
                hierarchical_return=hierarchical_return
            )
    r�Nrz<Policy is missing the required "key" or "name" attribute:
{}r�rTFrr�)r�r�r�r�r�r�rr$rr#)r�r�r�r�r�rrrRr)r�r�r�r�r)r�r�r�r�r�rrr�rr�rrrrr)r�r�r
r<rr�)r�r�r�rr)r�rrrr r!r�)r�r�r�rrFr"r#r+)r�r�r,r-r.rr/r�r0r1rCr2)6r�r�rr�r2rFrrrDr:r;r<r�r�r��
setdefaultr=r�rr�r�r�r>r�r
r�r�r�r?r@rArBr�r�rCrDr�r�r�r�r�r3r4r�r3r9rr�rEr�r�r�rirF),rOrGr�r�rHrTZthis_policy_nameZthis_value_namerQZthis_policy_namespacerRrSr�rNrJrLrKrUrVrWrXrYrZr[Zchild_value_namer]r^r�r_r`rar�rbrcrdr�rerfrg�t_dictrir��new_dictrkr�r�r��_get_policy_adm_setting.#s�5��
��
����
����
����
������
����	��
��

���
���
����

���

������
�
���
�
����
�
��
�
������
�
��

�����������'


��
�������
�
����;,�
��
��
��

���
��
���
��
��
���
�
��
�
���
�
�
���

�
��r�cCs�|std��|std��|��}t�}||jvr(d�|j���}td�||���d}||j|dvr=|j|d|}nP|j|dD]}	|j|d|	d}
|
|kr`|j|d|	}nqD|dur�|j|dD] }	|j|d|	d}
|
��|��kr�|j|d|	}nql|r�|r�t	|�S|r�|d}n|}|t	|�i}|r�d|vr�d	}
i}t
|d�D]}i}|
r�||�|�i||<d
}
n|||<|}q�|r�|}|St|||d�\}}}}|r�t
|||||d�}|r�|D]}||S|SdS)
a�
    Get the current settings for a single policy on the machine

    Args:
        policy_name (str):
            The name of the policy to retrieve. Can be the any of the names
            or alieses returned by ``lgpo.get_policy_info``

        policy_class (str):
            The policy class. Must be one of ``machine`` or ``user``

        adml_language (str):
            The language code for the adml file to use for localization. The
            default is ``en-US``

        return_value_only (bool):
            ``True`` will return only the value for the policy, without the
            name of the policy. ``return_full_policy_names`` and
            ``hierarchical_return`` will be ignored. Default is ``True``

        return_full_policy_names (bool):
            Returns the full policy name regardless of what was passed in
            ``policy_name``

            .. note::
                This setting applies to sub-elements of the policy if they
                exist. The value passed in ``policy_name`` will always be used
                as the policy name when this setting is ``False``

        hierarchical_return (bool):
            Returns a hierarchical view of the policy showing its parents

    Returns:
        dict: A dictionary containing the policy settings

    CLI Example:

    .. code-block:: bash

        # Using the policy id
        salt * lgpo.get_policy LockoutDuration machine
        salt * lgpo.get_policy AutoUpdateCfg machine

        # Using the full name
        salt * lgpo.get_policy "Account lockout duration" machine
        salt * lgpo.get_policy "Configure Automatic Updates" machine

        # Using full path and name
        salt * lgpo.get_policy "Windows Components\Windows Update\Configure Automatic Updates" machine
    zpolicy_name must be definedzpolicy_class must be definedr�r�Nr�rBrCTFr�)rOrGr�r�rH)rr�rr�r�r�rr�r�r�r�r3r�r�)r�rGr�Zreturn_value_onlyr�rHr�r�rr�r�Zkey_namer�rir�r�r�r�Z
policy_objrr�r�r�r��
get_policy�%s�:
����
���r�cCst||id||d�}|S)a�
    Set a single computer policy

    Args:
        name (str):
            The name of the policy to configure

        setting (str):
            The setting to configure the named policy with

        cumulative_rights_assignments (bool): Determine how user rights
            assignment policies are configured. If True, user right assignment
            specifications are simply added to the existing policy. If False,
            only the users specified will get the right (any existing will have
            the right revoked)

        adml_language (str): The language files to use for looking up
            Administrative Template policy data (i.e. how the policy is
            displayed in the GUI).  Defaults to 'en-US' (U.S. English).

    Returns:
        bool: True if successful, otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' lgpo.set_computer_policy LockoutDuration 1440
    N)�computer_policy�user_policy�cumulative_rights_assignmentsr��r)rr�r�r�r�r�r�r��set_computer_policyY&s �r�cCst||idd|d�}|S)a|
    Set a single user policy

    Args:

        name (str):
            The name of the policy to configure

        setting (str):
            The setting to configure the named policy with

        adml_language (str):
            The language files to use for looking up Administrative Template
            policy data (i.e. how the policy is displayed in the GUI). Defaults
            to 'en-US' (U.S. English).

    Returns:
        bool: True if successful, Otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' lgpo.set_user_policy "Control Panel\Display\Disable the Display Control Panel" Enabled
    NT)r�r�r�r�r�)rr�r�r�r�r�r��set_user_policy�&s�r�c/Cs�|rt|t�std��|rt|t�std��||d�}|�r�t|d�}|D�]�}i}i}i}	i}
i}i}i}
t�}||�r�||D�]�}d}|}||j|dvr\|j|d|}nP|j|dD]}|j|d|d}||kr|j|d|}|}qc|dur�|j|dD] }|j|d|d}|��|��kr�|j|d|}|}q�|�r�t||||j|d|dd	�}t||j|d|d
�s�td�	||||���d|vr�t
�d
|�||d�||<qBd|v�r t
�d|�|dd|v�rg||dd<||dd�d�
|dddt|�g��qBd|v�rEt
�d|�|�||dd|dd|ddt|�d��qBd|v�rZ|	�||ddt|�d��qBd|v�r�t
�d|�|dd|
v�rvi|
|dd<||
|dd|dd<qBd|v�r�t
�d|�||d�|
|<qB|||}t
�d |�t|||d!�\}}}}|�r�|jd"}|j|j}||v�r�i||<||||<nt|��|�r�|||v�r�|du�r�t
�d#t|||����t
�t|||����t|||���d$k�r�t|||���d%k�r�t|��r�t|||t��r�t|�D�]�}|D�]|}t
�d&|jd'�d}t||jd'd(|d)�}t
�d*|jd'|�||||v�r\|}n|jd'|||v�rn|jd'}ntd+�	||���d,|jv�r�|jd,��d-k�r�||||�s�td.�	|���t�|�jd/k�r�t||||t��s�td0�	|���n�t�|�jd1k�s�t�|�jd2k�rd3}d4}d5|jv�r�t|jd5�}d6|jv�r�t|jd6�}t||||�|k�s�t||||�|k�rtd7�	|||���n�t�|�jd8k�r:d9} |D]}!||||t||!jd:���k�r-d(} n�q| �s9td;�	|���n]t�|�jd<k�r{d=|jv�rg|jd=��d-k�rgt||||t��sftd>�	|���n0t||||t��sztd?�	|���nt�|�jd@k�r�t||||t��s�td?�	|���|||�|�||||jd'<�q-�q(qBtdA�	|���t|||���dBk�r�tdC�	|���qB|�rp|D]�}"t
�dD|"�||"dEdu�r||"dEdFk�rtdG||"dHddI||"dHddJ||"dHddK||"dE||"dHddL�}#nLtdM||"dHddI||"dHddJ||"dHddK�}#|#dN�rd|#dOdFk�rdtdP||"dHddI||"dHddJ||"dHddK�}#|#�snt dQ�	|"����q�|
�r�|
D]e}$d}%|�s�t!|
|$dHdd�}%|
|$dE�r�|
|$dED]}&t"|&|
|$dHdd�}#|#�s�tdR�	|$����q�|%�r�|%D]#}&|&|
|$dEv�r�t#|&|
|$dHdd�}#|#�s�tdS�	|$����q��qu|�r$t
�|�dT�
dUdVg�}'gdW�}(|(D]})|)|v�r
dT�
|'dX�
dY|)dZg�dT�
||)�g�}'�q�dT�
|'d[d\d]g�}'t
�d^|'�t$|'��s$t d_��|�rC|D]}*t
�d`|*�t
�||*�t%dhi||*���q)|	�rb|	D]}*t
�da|*�t
�|	|*�t&dhi|	|*���qH|
�r�t
�|
�|
D];}+zt'�(d|+�},t)�*|,|
|+�}-t
�db|-�t'�+d|+|-�}#W�qlt,�y�}.zdc�	|.�}t
�-|�t |��d}.~.ww|�r�d9}#t
�dd|�t.|||de�}#|#�s�t df��q%d(Stdg��)ia�
    Set a local server policy.

    Args:

        computer_policy (dict):
            A dictionary of "policyname: value" pairs of computer policies to
            set. 'value' should be how it is displayed in the gpedit GUI, i.e.
            if a setting can be 'Enabled'/'Disabled', then that should be passed

            Administrative Template data may require dicts within dicts, to
            specify each element of the Administrative Template policy.
            Administrative Templates policies are always cumulative.

            Policy names can be specified in a number of ways based on the type
            of policy:

                Windows Settings Policies:

                    These policies can be specified using the GUI display name
                    or the key name from the _policy_info class in this module.
                    The GUI display name is also contained in the _policy_info
                    class in this module.

                Administrative Template Policies:

                    These can be specified using the policy name as displayed in
                    the GUI (case sensitive). Some policies have the same name,
                    but a different location (for example, "Access data sources
                    across domains"). These can be differentiated by the "path"
                    in the GUI (for example, "Windows Components\Internet
                    Explorer\Internet Control Panel\Security Page\Internet
                    Zone\Access data sources across domains").

                    Additionally, policies can be specified using the "name" and
                    "id" attributes from the ADMX files.

                    For Administrative Templates that have policy elements, each
                    element can be specified using the text string as seen in
                    the GUI or using the ID attribute from the ADMX file. Due to
                    the way some of the GUI text is laid out, some policy
                    element names could include descriptive text that appears
                    lbefore the policy element in the GUI.

                    Use the get_policy_info function for the policy name to view
                    the element ID/names that the module will accept.

        user_policy (dict):
            The same setup as the computer_policy, except with data to configure
            the local user policy.

        cumulative_rights_assignments (bool):
            Determine how user rights assignment policies are configured.

            If True, user right assignment specifications are simply added to
            the existing policy

            If False, only the users specified will get the right (any existing
            will have the right revoked)

        adml_language (str):
            The language files to use for looking up Administrative Template
            policy data (i.e. how the policy is displayed in the GUI). Defaults
            to 'en-US' (U.S. English).

    Returns:
        bool: True is successful, otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' lgpo.set computer_policy="{'LockoutDuration': 2, 'RestrictAnonymous': 'Enabled', 'AuditProcessTracking': 'Succes, Failure'}"
    z+computer_policy must be specified as a dictz'user_policy must be specified as a dict)r�r=r�Nr�rBr)r�)rxr<zBThe specified value {} is not an acceptable setting for policy {}.rz%s is a registry policy)r<rxrPz%s is a Secedit policyr@r�rOr�r`z%s is a NetSH policyr_r�r�r~roz%s is a NetUserModal policyrnr�z%s is a LsaRights policyzsearching for "%s" in admx datar�rz
setting == %sr�r�zchecking element %sr�Trz/id attribute == "%s"  this_element_name == "%s"zGElement "{}" must be included in the policy configuration for policy {}�requiredrFz-Element "{}" requires a value to be specifiedr�z+Element {} requires a boolean True or Falser�r�ri'ZminValueZmaxValuez,Element "{}" value must be between {} and {}rFr�z(Element "{}" does not have a valid valuer�rz4Each list item of element "{}" requires a dict valuez"Element "{}" requires a list valuerz5The policy "{}" has elements which must be configured�enabledzGThe policy {} must either be "Enabled", "Disabled", or "Not Configured"z%s is a Registry policyrxr z
reg.set_valuer<rSrTrUrVr�r�r�zreg.delete_valuezfError while attempting to set policy {} via the registry.  Some changes may not be applied as expectedz<An error occurred attempting to configure the user right {}.zQAn error occurred attempting to remove previously configured users with right {}.rz	[Unicode]zUnicode=yes)rNr�r}zPrivilege Rightsr�r�r�z	[Version]zsignature="$CHICAGO$"z
Revision=1zini_data == %sz_Error while attempting to set policies via secedit. Some changes may not be applied as expectedzSetting firewall policy: %sz!Setting Advanced Audit policy: %szNEW MODAL SET = %szUAn unhandled exception occurred while attempting to set policy via NetUserModalSet
{}z+going to write some adm template data :: %s)r�rzqError while attempting to write Administrative Template Policy data.  Some changes may not be applied as expectedzYou have to specify something!r�)/r�r�rrDrr�r�r�r�r�r�r�r�r�r�r�r�r�r2rFr>r�r
r�r��boolr�r�r�r�r3rLrr�r�r�r�r�rr�r�rFriZNetUserModalsSetr�r�r�)/r�r�r�r�r�rNr�Z	_seceditsZ_netshsZ
_advauditsZ_modal_setsZ_admTemplateDataZ	_regeditsZ
_lsarightsr�r�r�Zpolicy_key_namer<r��_valuer�r�r�r�rdrXrYZtemp_element_namerZZmin_valZmax_valr�r^Zregeditr�ZlsarightZ_existingUsersZacctZini_dataZ_seceditSectionsZ_seceditSectionr�Z
_modal_setZ_existingModalDataZ_newModalSetDatar�r�r�r�r�&sXQ



�����
������
�



��
	
��
�
�
���

�

��
��
��
��

�
�������������	�������
��������
�
���������������	���
�����������
������������������
�������
���������d�������
���������������

���
�
�
��
��
������)r'r()N)F)T)FT)FN)r(FFF)r(r=)r()NTFr(F)r(FF)r(TTF)Tr()NNTr()�r�rM�ctypesrr��localerer�r�rvr5ZuuidrZsalt.utils.dictupdater�rFZsalt.utils.filesr�Zsalt.utils.pathZsalt.utils.platformZsalt.utils.stringutilsZsalt.utils.win_lgpo_netshZsalt.exceptionsrrZsalt.serializers.configparserrZsalt.utils.win_lgpo_regrrrrr	�	getLoggerr�r�r�Z__func_alias__Zuuid4�hexr�r�r�r?r@r>r:r<r=r;rCrArBr6r7r8r�rDZENUM_ITEM_DISPLAY_NAME_XPATHr�r�r�r�r�r�r�r�r�r
Zsalt.utils.win_regrr0ZwindllZkernel32�windows_localer�ZGetSystemDefaultUILanguager�r/�ImportErrorrr�r�r�rrrr&r=rArCrDrGrSrcrlr|r}rr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rlr9rsrzr�r�r�r�r�r�r�r�r�r�r�r�rr�r�r�r��<module>s�,














��
�����
���l

T
)


V
%%o/'
%
8
F
�Q
�,
�F
�N
�"$<0
 
�
2
:
[
�Z
�.
�
�
)$�