Merge pull request #50780 from twangboy/lgpo_netsh

Add netsh mechanism in the LGPO module
This commit is contained in:
Daniel Wozniak 2018-12-10 15:09:19 -07:00 committed by GitHub
commit 9b6b39ce49
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 2410 additions and 10 deletions

View file

@ -10,6 +10,7 @@ import re
# Import Salt libs
import salt.utils.platform
from salt.exceptions import CommandExecutionError
import salt.utils.win_lgpo_netsh
# Define the module's virtual name
__virtualname__ = 'firewall'
@ -285,7 +286,7 @@ def delete_rule(name=None,
salt '*' firewall.delete_rule 'test' '8080' 'tcp' 'in'
# Delete the incoming tcp port 8000 from 192.168.0.1 in the rule named
# 'test_remote_ip`
# 'test_remote_ip'
salt '*' firewall.delete_rule 'test_remote_ip' '8000' 'tcp' 'in' '192.168.0.1'
# Delete all rules for local port 80:
@ -342,3 +343,436 @@ def rule_exists(name):
return True
except CommandExecutionError:
return False
def get_settings(profile, section, store='local'):
'''
Get the firewall property from the specified profile in the specified store
as returned by ``netsh advfirewall``.
.. versionadded:: 2018.3.4
.. versionadded:: Fluorine
Args:
profile (str):
The firewall profile to query. Valid options are:
- domain
- public
- private
section (str):
The property to query within the selected profile. Valid options
are:
- firewallpolicy : inbound/outbound behavior
- logging : firewall logging settings
- settings : firewall properties
- state : firewalls state (on | off)
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
dict: A dictionary containing the properties for the specified profile
Raises:
CommandExecutionError: If an error occurs
ValueError: If the parameters are incorrect
CLI Example:
.. code-block:: bash
# Get the inbound/outbound firewall settings for connections on the
# local domain profile
salt * win_firewall.get_settings domain firewallpolicy
# Get the inbound/outbound firewall settings for connections on the
# domain profile as defined by local group policy
salt * win_firewall.get_settings domain firewallpolicy lgpo
'''
return salt.utils.win_lgpo_netsh.get_settings(profile=profile,
section=section,
store=store)
def get_all_settings(domain, store='local'):
'''
Gets all the properties for the specified profile in the specified store
.. versionadded:: 2018.3.4
.. versionadded:: Fluorine
Args:
profile (str):
The firewall profile to query. Valid options are:
- domain
- public
- private
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
dict: A dictionary containing the specified settings
CLI Example:
.. code-block:: bash
# Get all firewall settings for connections on the domain profile
salt * win_firewall.get_all_settings domain
# Get all firewall settings for connections on the domain profile as
# defined by local group policy
salt * win_firewall.get_all_settings domain lgpo
'''
return salt.utils.win_lgpo_netsh.get_all_settings(profile=domain,
store=store)
def get_all_profiles(store='local'):
'''
Gets all properties for all profiles in the specified store
.. versionadded:: 2018.3.4
.. versionadded:: Fluorine
Args:
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
dict: A dictionary containing the specified settings for each profile
CLI Example:
.. code-block:: bash
# Get all firewall settings for all profiles
salt * firewall.get_all_settings
# Get all firewall settings for all profiles as defined by local group
# policy
salt * firewall.get_all_settings lgpo
'''
return salt.utils.win_lgpo_netsh.get_all_profiles(store=store)
def set_firewall_settings(profile, inbound=None, outbound=None, store='local'):
'''
Set the firewall inbound/outbound settings for the specified profile and
store
.. versionadded:: 2018.3.4
.. versionadded:: Fluorine
Args:
profile (str):
The firewall profile to query. Valid options are:
- domain
- public
- private
inbound (str):
The inbound setting. If ``None`` is passed, the setting will remain
unchanged. Valid values are:
- blockinbound
- blockinboundalways
- allowinbound
- notconfigured
Default is ``None``
outbound (str):
The outbound setting. If ``None`` is passed, the setting will remain
unchanged. Valid values are:
- allowoutbound
- blockoutbound
- notconfigured
Default is ``None``
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
bool: ``True`` if successful
Raises:
CommandExecutionError: If an error occurs
ValueError: If the parameters are incorrect
CLI Example:
.. code-block:: bash
# Set the inbound setting for the domain profile to block inbound
# connections
salt * firewall.set_firewall_settings domain='domain' inbound='blockinbound'
# Set the outbound setting for the domain profile to allow outbound
# connections
salt * firewall.set_firewall_settings domain='domain' outbound='allowoutbound'
# Set inbound/outbound settings for the domain profile in the group
# policy to block inbound and allow outbound
salt * firewall.set_firewall_settings domain='domain' inbound='blockinbound' outbound='allowoutbound' store='lgpo'
'''
return salt.utils.win_lgpo_netsh.set_firewall_settings(profile=profile,
inbound=inbound,
outbound=outbound,
store=store)
def set_logging_settings(profile, setting, value, store='local'):
r'''
Configure logging settings for the Windows firewall.
.. versionadded:: 2018.3.4
.. versionadded:: Fluorine
Args:
profile (str):
The firewall profile to configure. Valid options are:
- domain
- public
- private
setting (str):
The logging setting to configure. Valid options are:
- allowedconnections
- droppedconnections
- filename
- maxfilesize
value (str):
The value to apply to the setting. Valid values are dependent upon
the setting being configured. Valid options are:
allowedconnections:
- enable
- disable
- notconfigured
droppedconnections:
- enable
- disable
- notconfigured
filename:
- Full path and name of the firewall log file
- notconfigured
maxfilesize:
- 1 - 32767
- notconfigured
.. note::
``notconfigured`` can only be used when using the lgpo store
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
bool: ``True`` if successful
Raises:
CommandExecutionError: If an error occurs
ValueError: If the parameters are incorrect
CLI Example:
.. code-block:: bash
# Log allowed connections and set that in local group policy
salt * firewall.set_logging_settings domain allowedconnections enable lgpo
# Don't log dropped connections
salt * firewall.set_logging_settings profile=private setting=droppedconnections value=disable
# Set the location of the log file
salt * firewall.set_logging_settings domain filename C:\windows\logs\firewall.log
# You can also use environment variables
salt * firewall.set_logging_settings domain filename %systemroot%\system32\LogFiles\Firewall\pfirewall.log
# Set the max file size of the log to 2048 Kb
salt * firewall.set_logging_settings domain maxfilesize 2048
'''
return salt.utils.win_lgpo_netsh.set_logging_settings(profile=profile,
setting=setting,
value=value,
store=store)
def set_settings(profile, setting, value, store='local'):
'''
Configure firewall settings.
.. versionadded:: 2018.3.4
.. versionadded:: Fluorine
Args:
profile (str):
The firewall profile to configure. Valid options are:
- domain
- public
- private
setting (str):
The firewall setting to configure. Valid options are:
- localfirewallrules
- localconsecrules
- inboundusernotification
- remotemanagement
- unicastresponsetomulticast
value (str):
The value to apply to the setting. Valid options are
- enable
- disable
- notconfigured
.. note::
``notconfigured`` can only be used when using the lgpo store
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
bool: ``True`` if successful
Raises:
CommandExecutionError: If an error occurs
ValueError: If the parameters are incorrect
CLI Example:
.. code-block:: bash
# Merge local rules with those distributed through group policy
salt * firewall.set_settings domain localfirewallrules enable
# Allow remote management of Windows Firewall
salt * firewall.set_settings domain remotemanagement enable
'''
return salt.utils.win_lgpo_netsh.set_settings(profile=profile,
setting=setting,
value=value,
store=store)
def set_state(profile, state, store='local'):
'''
Configure the firewall state.
.. versionadded:: 2018.3.4
.. versionadded:: Fluorine
Args:
profile (str):
The firewall profile to configure. Valid options are:
- domain
- public
- private
state (str):
The firewall state. Valid options are:
- on
- off
- notconfigured
.. note::
``notconfigured`` can only be used when using the lgpo store
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
bool: ``True`` if successful
Raises:
CommandExecutionError: If an error occurs
ValueError: If the parameters are incorrect
CLI Example:
.. code-block:: bash
# Turn the firewall off when the domain profile is active
salt * firewall.set_state domain off
# Turn the firewall on when the public profile is active and set that in
# the local group policy
salt * firewall.set_state public on lgpo
'''
return salt.utils.win_lgpo_netsh.set_state(profile=profile,
state=state,
store=store)

View file

@ -55,6 +55,7 @@ import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.win_lgpo_netsh
# Import 3rd-party libs
from salt.ext import six
@ -136,7 +137,7 @@ except ImportError:
class _policy_info(object):
'''
r'''
Policy Helper Class
===================
@ -224,7 +225,7 @@ class _policy_info(object):
Access"
======= ===================================================================
LsaRights mechanism
LsaRights Mechanism
-------------------
LSA Rights policies are configured via the LsaRights mechanism. The value of
@ -237,7 +238,7 @@ class _policy_info(object):
**SeNetworkLogonRight**
====== ====================================================================
NetUserModal mechanism
NetUserModal Mechanism
----------------------
Some policies are configurable by the **NetUserModalGet** and
@ -254,6 +255,34 @@ class _policy_info(object):
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
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:
@ -368,6 +397,13 @@ class _policy_info(object):
'Local Policies',
'Security Options'
]
self.windows_firewall_gpedit_path = [
'Computer Configuration',
'Windows Settings',
'Security Settings',
'Windows Firewall with Advanced Security',
'Windows Firewall with Advanced Security - Local Group Policy Object'
]
self.password_policy_gpedit_path = [
'Computer Configuration',
'Windows Settings',
@ -436,6 +472,37 @@ class _policy_info(object):
None: 'Not Defined',
'(value not set)': 'Not Defined'
}
self.firewall_inbound_connections = {
'blockinbound': 'Block (default)',
'blockinboundalways': 'Block all connections',
'allowinbound': 'Allow',
'notconfigured': 'Not configured'
}
self.firewall_outbound_connections = {
'blockoutbound': 'Block',
'allowoutbound': 'Allow (default)',
'notconfigured': 'Not configured'
}
self.firewall_rule_merging = {
'enable': 'Yes (default)',
'disable': 'No',
'notconfigured': 'Not configured'
}
self.firewall_log_packets_connections = {
'enable': 'Yes',
'disable': 'No (default)',
'notconfigured': 'Not configured'
}
self.firewall_notification = {
'enable': 'Yes',
'disable': 'No',
'notconfigured': 'Not configured'
}
self.firewall_state = {
'on': 'On (recommended)',
'off': 'Off',
'notconfigured': 'Not configured'
}
self.krb_encryption_types = {
0: 'No minimum',
1: 'DES_CBC_CRC',
@ -817,6 +884,717 @@ class _policy_info(object):
},
},
},
'WfwDomainState': {
'Policy': 'Network firewall: Domain: State',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - On (recommended)
# - Off
# - Not configured
'Settings': self.firewall_state.keys(),
'NetSH': {
'Profile': 'domain',
'Section': 'state',
'Option': 'State' # Unused, but needed
},
'Transform': {
'Get': '_dict_lookup',
'Put': '_dict_lookup',
'GetArgs': {
'lookup': self.firewall_state,
'value_lookup': False,
},
'PutArgs': {
'lookup': self.firewall_state,
'value_lookup': True,
},
},
},
'WfwPrivateState': {
'Policy': 'Network firewall: Private: State',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - On (recommended)
# - Off
# - Not configured
'Settings': self.firewall_state.keys(),
'NetSH': {
'Profile': 'private',
'Section': 'state',
'Option': 'State' # Unused, but needed
},
'Transform': {
'Get': '_dict_lookup',
'Put': '_dict_lookup',
'GetArgs': {
'lookup': self.firewall_state,
'value_lookup': False,
},
'PutArgs': {
'lookup': self.firewall_state,
'value_lookup': True,
},
},
},
'WfwPublicState': {
'Policy': 'Network firewall: Public: State',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - On (recommended)
# - Off
# - Not configured
'Settings': self.firewall_state.keys(),
'NetSH': {
'Profile': 'public',
'Section': 'state',
'Option': 'State' # Unused, but needed
},
'Transform': {
'Get': '_dict_lookup',
'Put': '_dict_lookup',
'GetArgs': {
'lookup': self.firewall_state,
'value_lookup': False,
},
'PutArgs': {
'lookup': self.firewall_state,
'value_lookup': True,
},
},
},
'WfwDomainInboundConnections': {
'Policy': 'Network firewall: Domain: Inbound connections',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - Block (default)
# - Block all connections
# - Allow
# - Not configured
'Settings': self.firewall_inbound_connections.keys(),
'NetSH': {
'Profile': 'domain',
'Section': 'firewallpolicy',
'Option': 'Inbound'
},
'Transform': {
'Get': '_dict_lookup',
'Put': '_dict_lookup',
'GetArgs': {
'lookup': self.firewall_inbound_connections,
'value_lookup': False,
},
'PutArgs': {
'lookup': self.firewall_inbound_connections,
'value_lookup': True,
},
},
},
'WfwPrivateInboundConnections': {
'Policy': 'Network firewall: Private: Inbound connections',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - Block (default)
# - Block all connections
# - Allow
# - Not configured
'Settings': self.firewall_inbound_connections.keys(),
'NetSH': {
'Profile': 'private',
'Section': 'firewallpolicy',
'Option': 'Inbound'
},
'Transform': {
'Get': '_dict_lookup',
'Put': '_dict_lookup',
'GetArgs': {
'lookup': self.firewall_inbound_connections,
'value_lookup': False,
},
'PutArgs': {
'lookup': self.firewall_inbound_connections,
'value_lookup': True,
},
},
},
'WfwPublicInboundConnections': {
'Policy': 'Network firewall: Public: Inbound connections',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - Block (default)
# - Block all connections
# - Allow
# - Not configured
'Settings': self.firewall_inbound_connections.keys(),
'NetSH': {
'Profile': 'public',
'Section': 'firewallpolicy',
'Option': 'Inbound'
},
'Transform': {
'Get': '_dict_lookup',
'Put': '_dict_lookup',
'GetArgs': {
'lookup': self.firewall_inbound_connections,
'value_lookup': False,
},
'PutArgs': {
'lookup': self.firewall_inbound_connections,
'value_lookup': True,
},
},
},
'WfwDomainOutboundConnections': {
'Policy': 'Network firewall: Domain: Outbound connections',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - Block
# - Allow (default)
# - Not configured
'Settings': self.firewall_outbound_connections.keys(),
'NetSH': {
'Profile': 'domain',
'Section': 'firewallpolicy',
'Option': 'Outbound'
},
'Transform': {
'Get': '_dict_lookup',
'Put': '_dict_lookup',
'GetArgs': {
'lookup': self.firewall_outbound_connections,
'value_lookup': False,
},
'PutArgs': {
'lookup': self.firewall_outbound_connections,
'value_lookup': True,
},
},
},
'WfwPrivateOutboundConnections': {
'Policy': 'Network firewall: Private: Outbound connections',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - Block
# - Allow (default)
# - Not configured
'Settings': self.firewall_outbound_connections.keys(),
'NetSH': {
'Profile': 'private',
'Section': 'firewallpolicy',
'Option': 'Outbound'
},
'Transform': {
'Get': '_dict_lookup',
'Put': '_dict_lookup',
'GetArgs': {
'lookup': self.firewall_outbound_connections,
'value_lookup': False,
},
'PutArgs': {
'lookup': self.firewall_outbound_connections,
'value_lookup': True,
},
},
},
'WfwPublicOutboundConnections': {
'Policy': 'Network firewall: Public: Outbound connections',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - Block
# - Allow (default)
# - Not configured
'Settings': self.firewall_outbound_connections.keys(),
'NetSH': {
'Profile': 'public',
'Section': 'firewallpolicy',
'Option': 'Outbound'
},
'Transform': {
'Get': '_dict_lookup',
'Put': '_dict_lookup',
'GetArgs': {
'lookup': self.firewall_outbound_connections,
'value_lookup': False,
},
'PutArgs': {
'lookup': self.firewall_outbound_connections,
'value_lookup': True,
},
},
},
'WfwDomainSettingsNotification': {
'Policy': 'Network firewall: Domain: Settings: Display a notification',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - Yes
# - No
# - Not configured
'Settings': self.firewall_notification.keys(),
'NetSH': {
'Profile': 'domain',
'Section': 'settings',
'Option': 'InboundUserNotification'
},
'Transform': {
'Get': '_dict_lookup',
'Put': '_dict_lookup',
'GetArgs': {
'lookup': self.firewall_notification,
'value_lookup': False,
},
'PutArgs': {
'lookup': self.firewall_notification,
'value_lookup': True,
},
},
},
'WfwPrivateSettingsNotification': {
'Policy': 'Network firewall: Private: Settings: Display a notification',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - Yes
# - No
# - Not configured
'Settings': self.firewall_notification.keys(),
'NetSH': {
'Profile': 'private',
'Section': 'settings',
'Option': 'InboundUserNotification'
},
'Transform': {
'Get': '_dict_lookup',
'Put': '_dict_lookup',
'GetArgs': {
'lookup': self.firewall_notification,
'value_lookup': False,
},
'PutArgs': {
'lookup': self.firewall_notification,
'value_lookup': True,
},
},
},
'WfwPublicSettingsNotification': {
'Policy': 'Network firewall: Public: Settings: Display a notification',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - Yes
# - No
# - Not configured
'Settings': self.firewall_notification.keys(),
'NetSH': {
'Profile': 'public',
'Section': 'settings',
'Option': 'InboundUserNotification'
},
'Transform': {
'Get': '_dict_lookup',
'Put': '_dict_lookup',
'GetArgs': {
'lookup': self.firewall_notification,
'value_lookup': False,
},
'PutArgs': {
'lookup': self.firewall_notification,
'value_lookup': True,
},
},
},
'WfwDomainSettingsLocalFirewallRules': {
'Policy': 'Network firewall: Domain: Settings: Apply '
'local firewall rules',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - Yes (default)
# - No
# - Not configured
'Settings': self.firewall_rule_merging.keys(),
'NetSH': {
'Profile': 'domain',
'Section': 'settings',
'Option': 'LocalFirewallRules'
},
'Transform': {
'Get': '_dict_lookup',
'Put': '_dict_lookup',
'GetArgs': {
'lookup': self.firewall_rule_merging,
'value_lookup': False,
},
'PutArgs': {
'lookup': self.firewall_rule_merging,
'value_lookup': True,
},
},
},
'WfwPrivateSettingsLocalFirewallRules': {
'Policy': 'Network firewall: Private: Settings: Apply '
'local firewall rules',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - Yes (default)
# - No
# - Not configured
'Settings': self.firewall_rule_merging.keys(),
'NetSH': {
'Profile': 'private',
'Section': 'settings',
'Option': 'LocalFirewallRules'
},
'Transform': {
'Get': '_dict_lookup',
'Put': '_dict_lookup',
'GetArgs': {
'lookup': self.firewall_rule_merging,
'value_lookup': False,
},
'PutArgs': {
'lookup': self.firewall_rule_merging,
'value_lookup': True,
},
},
},
'WfwPublicSettingsLocalFirewallRules': {
'Policy': 'Network firewall: Public: Settings: Apply '
'local firewall rules',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - Yes (default)
# - No
# - Not configured
'Settings': self.firewall_rule_merging.keys(),
'NetSH': {
'Profile': 'public',
'Section': 'settings',
'Option': 'LocalFirewallRules'
},
'Transform': {
'Get': '_dict_lookup',
'Put': '_dict_lookup',
'GetArgs': {
'lookup': self.firewall_rule_merging,
'value_lookup': False,
},
'PutArgs': {
'lookup': self.firewall_rule_merging,
'value_lookup': True,
},
},
},
'WfwDomainSettingsLocalConnectionRules': {
'Policy': 'Network firewall: Domain: Settings: Apply '
'local connection security rules',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - Yes (default)
# - No
# - Not configured
'Settings': self.firewall_rule_merging.keys(),
'NetSH': {
'Profile': 'domain',
'Section': 'settings',
'Option': 'LocalConSecRules'
},
'Transform': {
'Get': '_dict_lookup',
'Put': '_dict_lookup',
'GetArgs': {
'lookup': self.firewall_rule_merging,
'value_lookup': False,
},
'PutArgs': {
'lookup': self.firewall_rule_merging,
'value_lookup': True,
},
},
},
'WfwPrivateSettingsLocalConnectionRules': {
'Policy': 'Network firewall: Private: Settings: Apply '
'local connection security rules',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - Yes (default)
# - No
# - Not configured
'Settings': self.firewall_rule_merging.keys(),
'NetSH': {
'Profile': 'private',
'Section': 'settings',
'Option': 'LocalConSecRules'
},
'Transform': {
'Get': '_dict_lookup',
'Put': '_dict_lookup',
'GetArgs': {
'lookup': self.firewall_rule_merging,
'value_lookup': False,
},
'PutArgs': {
'lookup': self.firewall_rule_merging,
'value_lookup': True,
},
},
},
'WfwPublicSettingsLocalConnectionRules': {
'Policy': 'Network firewall: Public: Settings: Apply '
'local connection security rules',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - Yes (default)
# - No
# - Not configured
'Settings': self.firewall_rule_merging.keys(),
'NetSH': {
'Profile': 'public',
'Section': 'settings',
'Option': 'LocalConSecRules'
},
'Transform': {
'Get': '_dict_lookup',
'Put': '_dict_lookup',
'GetArgs': {
'lookup': self.firewall_rule_merging,
'value_lookup': False,
},
'PutArgs': {
'lookup': self.firewall_rule_merging,
'value_lookup': True,
},
},
},
'WfwDomainLoggingName': {
'Policy': 'Network firewall: Domain: Logging: Name',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - <a full path to a file>
# - Not configured
'Settings': None,
'NetSH': {
'Profile': 'domain',
'Section': 'logging',
'Option': 'FileName'
}
},
'WfwPrivateLoggingName': {
'Policy': 'Network firewall: Private: Logging: Name',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - <a full path to a file>
# - Not configured
'Settings': None,
'NetSH': {
'Profile': 'private',
'Section': 'logging',
'Option': 'FileName'
}
},
'WfwPublicLoggingName': {
'Policy': 'Network firewall: Public: Logging: Name',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - <a full path to a file>
# - Not configured
'Settings': None,
'NetSH': {
'Profile': 'public',
'Section': 'logging',
'Option': 'FileName'
}
},
'WfwDomainLoggingMaxFileSize': {
'Policy': 'Network firewall: Domain: Logging: Size limit (KB)',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - <int between 1 and 32767>
# - Not configured
'Settings': None,
'NetSH': {
'Profile': 'domain',
'Section': 'logging',
'Option': 'MaxFileSize'
}
},
'WfwPrivateLoggingMaxFileSize': {
'Policy': 'Network firewall: Private: Logging: Size limit (KB)',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - <int between 1 and 32767>
# - Not configured
'Settings': None,
'NetSH': {
'Profile': 'private',
'Section': 'logging',
'Option': 'MaxFileSize'
}
},
'WfwPublicLoggingMaxFileSize': {
'Policy': 'Network firewall: Public: Logging: Size limit (KB)',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - <int between 1 and 32767>
# - Not configured
'Settings': None,
'NetSH': {
'Profile': 'public',
'Section': 'logging',
'Option': 'MaxFileSize'
}
},
'WfwDomainLoggingAllowedConnections': {
'Policy': 'Network firewall: Domain: Logging: Log successful connections',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - Yes
# - No (default)
# - Not configured
'Settings': self.firewall_log_packets_connections.keys(),
'NetSH': {
'Profile': 'domain',
'Section': 'logging',
'Option': 'LogAllowedConnections'
},
'Transform': {
'Get': '_dict_lookup',
'Put': '_dict_lookup',
'GetArgs': {
'lookup': self.firewall_log_packets_connections,
'value_lookup': False,
},
'PutArgs': {
'lookup': self.firewall_log_packets_connections,
'value_lookup': True,
},
},
},
'WfwPrivateLoggingAllowedConnections': {
'Policy': 'Network firewall: Private: Logging: Log successful connections',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - Yes
# - No (default)
# - Not configured
'Settings': self.firewall_log_packets_connections.keys(),
'NetSH': {
'Profile': 'private',
'Section': 'logging',
'Option': 'LogAllowedConnections'
},
'Transform': {
'Get': '_dict_lookup',
'Put': '_dict_lookup',
'GetArgs': {
'lookup': self.firewall_log_packets_connections,
'value_lookup': False,
},
'PutArgs': {
'lookup': self.firewall_log_packets_connections,
'value_lookup': True,
},
},
},
'WfwPublicLoggingAllowedConnections': {
'Policy': 'Network firewall: Public: Logging: Log successful connections',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - Yes
# - No (default)
# - Not configured
'Settings': self.firewall_log_packets_connections.keys(),
'NetSH': {
'Profile': 'public',
'Section': 'logging',
'Option': 'LogAllowedConnections'
},
'Transform': {
'Get': '_dict_lookup',
'Put': '_dict_lookup',
'GetArgs': {
'lookup': self.firewall_log_packets_connections,
'value_lookup': False,
},
'PutArgs': {
'lookup': self.firewall_log_packets_connections,
'value_lookup': True,
},
},
},
'WfwDomainLoggingDroppedConnections': {
'Policy': 'Network firewall: Domain: Logging: Log dropped packets',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - Yes
# - No (default)
# - Not configured
'Settings': self.firewall_log_packets_connections.keys(),
'NetSH': {
'Profile': 'domain',
'Section': 'logging',
'Option': 'LogDroppedConnections'
},
'Transform': {
'Get': '_dict_lookup',
'Put': '_dict_lookup',
'GetArgs': {
'lookup': self.firewall_log_packets_connections,
'value_lookup': False,
},
'PutArgs': {
'lookup': self.firewall_log_packets_connections,
'value_lookup': True,
},
},
},
'WfwPrivateLoggingDroppedConnections': {
'Policy': 'Network firewall: Private: Logging: Log dropped packets',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - Yes
# - No (default)
# - Not configured
'Settings': self.firewall_log_packets_connections.keys(),
'NetSH': {
'Profile': 'private',
'Section': 'logging',
'Option': 'LogDroppedConnections'
},
'Transform': {
'Get': '_dict_lookup',
'Put': '_dict_lookup',
'GetArgs': {
'lookup': self.firewall_log_packets_connections,
'value_lookup': False,
},
'PutArgs': {
'lookup': self.firewall_log_packets_connections,
'value_lookup': True,
},
},
},
'WfwPublicLoggingDroppedConnections': {
'Policy': 'Network firewall: Public: Logging: Log dropped packets',
'lgpo_section': self.windows_firewall_gpedit_path,
# Settings available are:
# - Yes
# - No (default)
# - Not configured
'Settings': self.firewall_log_packets_connections.keys(),
'NetSH': {
'Profile': 'public',
'Section': 'logging',
'Option': 'LogDroppedConnections'
},
'Transform': {
'Get': '_dict_lookup',
'Put': '_dict_lookup',
'GetArgs': {
'lookup': self.firewall_log_packets_connections,
'value_lookup': False,
},
'PutArgs': {
'lookup': self.firewall_log_packets_connections,
'value_lookup': True,
},
},
},
'PasswordHistory': {
'Policy': 'Enforce password history',
'lgpo_section': self.password_policy_gpedit_path,
@ -3571,6 +4349,54 @@ def _buildElementNsmap(using_elements):
return thisMap
def _findOptionValueNetSH(profile, option):
if 'lgpo.netsh_data' not in __context__:
__context__['lgpo.netsh_data'] = {}
if profile not in __context__['lgpo.netsh_data']:
log.debug('LGPO: Loading netsh data for {0} profile'.format(profile))
settings = salt.utils.win_lgpo_netsh.get_all_settings(profile=profile,
store='lgpo')
__context__['lgpo.netsh_data'].update({profile: settings})
log.debug('LGPO: netsh returning value: {0}'
''.format(__context__['lgpo.netsh_data'][profile][option]))
return __context__['lgpo.netsh_data'][profile][option]
def _setOptionValueNetSH(profile, section, option, value):
if section not in ('firewallpolicy', 'settings', 'logging', 'state'):
raise ValueError('LGPO: Invalid section: {0}'.format(section))
log.debug('LGPO: Setting the following\n'
'Profile: {0}\n'
'Section: {1}\n'
'Option: {2}\n'
'Value: {3}'.format(profile, section, option, value))
if section == 'firewallpolicy':
salt.utils.win_lgpo_netsh.set_firewall_settings(
profile=profile,
inbound=value if option == 'Inbound' else None,
outbound=value if option == 'Outbound' else None,
store='lgpo')
if section == 'settings':
salt.utils.win_lgpo_netsh.set_settings(
profile=profile, setting=option, value=value, store='lgpo')
if section == 'state':
salt.utils.win_lgpo_netsh.set_state(
profile=profile, state=value, store='lgpo')
if section == 'logging':
if option in ('FileName', 'MaxFileSize'):
if value == 'Not configured':
value = 'notconfigured'
# Trim log for the two logging options
if option.startswith('Log'):
option = option[3:]
salt.utils.win_lgpo_netsh.set_logging_settings(
profile=profile, setting=option, value=value, store='lgpo')
log.debug('LGPO: Clearing netsh data for {0} profile'.format(profile))
__context__['lgpo.netsh_data'].pop(profile)
return True
def _findOptionValueInSeceditFile(option):
'''
helper function to dump/parse a `secedit /export` file for a particular option
@ -5939,6 +6765,12 @@ def get(policy_class=None, return_full_policy_names=True,
else:
msg = 'An error occurred attempting to get the value of policy {0} from secedit'
raise CommandExecutionError(msg.format(policy_name))
elif 'NetSH' in _pol:
# get value from netsh
class_vals[policy_name] = _findOptionValueNetSH(
profile=_pol['NetSH']['Profile'],
option=_pol['NetSH']['Option'])
elif 'NetUserModal' in _pol:
# get value from UserNetMod
if _pol['NetUserModal']['Modal'] not in modal_returns:
@ -6160,6 +6992,7 @@ def set_(computer_policy=None, user_policy=None,
if policies:
for p_class in policies:
_secedits = {}
_netshs = {}
_modal_sets = {}
_admTemplateData = {}
_regedits = {}
@ -6199,6 +7032,15 @@ def set_(computer_policy=None, user_policy=None,
_secedits[_pol['Secedit']['Section']].append(
' '.join([_pol['Secedit']['Option'],
'=', six.text_type(_value)]))
elif 'NetSH' in _pol:
# set value with netsh
log.debug('%s is a NetSH policy', policy_name)
_netshs.setdefault(policy_name, {
'profile': _pol['NetSH']['Profile'],
'section': _pol['NetSH']['Section'],
'option': _pol['NetSH']['Option'],
'value': six.text_type(_value)
})
elif 'NetUserModal' in _pol:
# set value via NetUserModal
log.debug('%s is a NetUserModal policy', policy_name)
@ -6388,6 +7230,13 @@ def set_(computer_policy=None, user_policy=None,
msg = ('Error while attempting to set policies via secedit.'
' Some changes may not be applied as expected')
raise CommandExecutionError(msg)
if _netshs:
# we've got netsh settings to make
for setting in _netshs:
log.debug('Setting firewall policy: {0}'.format(setting))
log.debug(_netshs[setting])
_setOptionValueNetSH(**_netshs[setting])
if _modal_sets:
# we've got modalsets to make
log.debug(_modal_sets)

View file

@ -308,13 +308,13 @@ def set_(name,
policy_changes.append(policy_name)
else:
if additional_policy_comments:
ret['comment'] = '"{0}" is already set ({1}).\n'.format(policy_name, ', '.join(additional_policy_comments))
ret['comment'] = '"{0}" is already set ({1})\n'.format(policy_name, ', '.join(additional_policy_comments))
else:
ret['comment'] = '"{0}" is already set.\n'.format(policy_name) + ret['comment']
ret['comment'] = '"{0}" is already set\n'.format(policy_name) + ret['comment']
else:
log.debug('%s current setting matches '
'the requested setting', policy_name)
ret['comment'] = '"{0}" is already set.\n'.format(policy_name) + ret['comment']
ret['comment'] = '"{0}" is already set\n'.format(policy_name) + ret['comment']
else:
policy_changes.append(policy_name)
log.debug('policy %s is not set, we will configure it',
@ -322,7 +322,7 @@ def set_(name,
if __opts__['test']:
if policy_changes:
ret['result'] = None
ret['comment'] = 'The following policies are set to change:\n{0}.'.format(
ret['comment'] = 'The following policies are set to change:\n{0}'.format(
'\n'.join(policy_changes))
else:
ret['comment'] = 'All specified policies are properly configured'
@ -334,13 +334,17 @@ def set_(name,
adml_language=adml_language)
if _ret:
ret['result'] = _ret
ret['comment'] = 'The following policies changed:\n{0}.'.format(
'\n'.join(policy_changes))
ret['changes'] = salt.utils.dictdiffer.deep_diff(
current_policy,
__salt__['lgpo.get'](policy_class=policy_class,
adml_language=adml_language,
hierarchical_return=False))
if ret['changes']:
ret['comment'] = 'The following policies changed:\n{0}' \
''.format('\n'.join(policy_changes))
else:
ret['comment'] = 'The following policies are in the correct state:\n{0}' \
''.format('\n'.join(policy_changes))
else:
ret['result'] = False
ret['comment'] = 'Errors occurred while attempting to configure policies: {0}'.format(_ret)

View file

@ -0,0 +1,578 @@
# -*- coding: utf-8 -*-
r'''
A salt util for modifying firewall settings.
.. versionadded:: 2018.3.4
.. versionadded:: Fluorine
This util allows you to modify firewall settings in the local group policy in
addition to the normal firewall settings. Parameters are taken from the
netsh advfirewall prompt.
.. note::
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
Usage:
.. code-block:: python
import salt.utils.win_lgpo_netsh
# Get the inbound/outbound firewall settings for connections on the
# local domain profile
salt.utils.win_lgpo_netsh.get_settings(profile='domain',
section='firewallpolicy')
# Get the inbound/outbound firewall settings for connections on the
# domain profile as defined by local group policy
salt.utils.win_lgpo_netsh.get_settings(profile='domain',
section='firewallpolicy',
store='lgpo')
# Get all firewall settings for connections on the domain profile
salt.utils.win_lgpo_netsh.get_all_settings(profile='domain')
# Get all firewall settings for connections on the domain profile as
# defined by local group policy
salt.utils.win_lgpo_netsh.get_all_settings(profile='domain', store='lgpo')
# Get all firewall settings for all profiles
salt.utils.win_lgpo_netsh.get_all_settings()
# Get all firewall settings for all profiles as defined by local group
# policy
salt.utils.win_lgpo_netsh.get_all_settings(store='lgpo')
# Set the inbound setting for the domain profile to block inbound
# connections
salt.utils.win_lgpo_netsh.set_firewall_settings(profile='domain',
inbound='blockinbound')
# Set the outbound setting for the domain profile to allow outbound
# connections
salt.utils.win_lgpo_netsh.set_firewall_settings(profile='domain',
outbound='allowoutbound')
# Set inbound/outbound settings for the domain profile in the group
# policy to block inbound and allow outbound
salt.utils.win_lgpo_netsh.set_firewall_settings(profile='domain',
inbound='blockinbound',
outbound='allowoutbound',
store='lgpo')
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from textwrap import dedent
import logging
import os
import re
import socket
import tempfile
import salt.modules.cmdmod
from salt.exceptions import CommandExecutionError
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__hostname__ = socket.gethostname()
def _netsh_file(content):
'''
helper function to get the results of ``netsh -f content.txt``
Running ``netsh`` will drop you into a ``netsh`` prompt where you can issue
``netsh`` commands. You can put a series of commands in an external file and
run them as if from a ``netsh`` prompt using the ``-f`` switch. That's what
this function does.
Args:
content (str):
The contents of the file that will be run by the ``netsh -f``
command
Returns:
str: The text returned by the netsh command
'''
with tempfile.NamedTemporaryFile(mode='w',
prefix='salt-',
suffix='.netsh',
delete=False) as fp:
fp.write(content)
try:
log.debug('{0}:\n{1}'.format(fp.name, content))
return salt.modules.cmdmod.run('netsh -f {0}'.format(fp.name), python_shell=True)
finally:
os.remove(fp.name)
def _netsh_command(command, store):
if store.lower() not in ('local', 'lgpo'):
raise ValueError('Incorrect store: {0}'.format(store))
# set the store for local or lgpo
if store.lower() == 'local':
netsh_script = dedent('''\
advfirewall
set store local
{0}
'''.format(command))
else:
netsh_script = dedent('''\
advfirewall
set store gpo = {0}
{1}
'''.format(__hostname__, command))
return _netsh_file(content=netsh_script).splitlines()
def get_settings(profile, section, store='local'):
'''
Get the firewall property from the specified profile in the specified store
as returned by ``netsh advfirewall``.
Args:
profile (str):
The firewall profile to query. Valid options are:
- domain
- public
- private
section (str):
The property to query within the selected profile. Valid options
are:
- firewallpolicy : inbound/outbound behavior
- logging : firewall logging settings
- settings : firewall properties
- state : firewalls state (on | off)
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
dict: A dictionary containing the properties for the specified profile
Raises:
CommandExecutionError: If an error occurs
ValueError: If the parameters are incorrect
'''
# validate input
if profile.lower() not in ('domain', 'public', 'private'):
raise ValueError('Incorrect profile: {0}'.format(profile))
if section.lower() not in ('state', 'firewallpolicy', 'settings', 'logging'):
raise ValueError('Incorrect section: {0}'.format(section))
if store.lower() not in ('local', 'lgpo'):
raise ValueError('Incorrect store: {0}'.format(store))
command = 'show {0}profile {1}'.format(profile, section)
# run it
results = _netsh_command(command=command, store=store)
# sample output:
# Domain Profile Settings:
# ----------------------------------------------------------------------
# LocalFirewallRules N/A (GPO-store only)
# LocalConSecRules N/A (GPO-store only)
# InboundUserNotification Disable
# RemoteManagement Disable
# UnicastResponseToMulticast Enable
# if it's less than 3 lines it failed
if len(results) < 3:
raise CommandExecutionError('Invalid results: {0}'.format(results))
ret = {}
# Skip the first 2 lines. Add everything else to a dictionary
for line in results[3:]:
ret.update(dict(map(None, *[iter(re.split(r"\s{2,}", line))]*2))) # pylint: disable=incompatible-py3-code
# Remove spaces from the values so that `Not Configured` is detected
# correctly
for item in ret:
ret[item] = ret[item].replace(' ', '')
# special handling for firewallpolicy
if section == 'firewallpolicy':
inbound, outbound = ret['Firewall Policy'].split(',')
return {'Inbound': inbound, 'Outbound': outbound}
return ret
def get_all_settings(profile, store='local'):
'''
Gets all the properties for the specified profile in the specified store
Args:
profile (str):
The firewall profile to query. Valid options are:
- domain
- public
- private
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
dict: A dictionary containing the specified settings
'''
ret = dict()
ret.update(get_settings(profile=profile, section='state', store=store))
ret.update(get_settings(profile=profile, section='firewallpolicy', store=store))
ret.update(get_settings(profile=profile, section='settings', store=store))
ret.update(get_settings(profile=profile, section='logging', store=store))
return ret
def get_all_profiles(store='local'):
'''
Gets all properties for all profiles in the specified store
Args:
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
dict: A dictionary containing the specified settings for each profile
'''
return {
'Domain Profile': get_all_settings(profile='domain', store=store),
'Private Profile': get_all_settings(profile='private', store=store),
'Public Profile': get_all_settings(profile='public', store=store)
}
def set_firewall_settings(profile,
inbound=None,
outbound=None,
store='local'):
'''
Set the firewall inbound/outbound settings for the specified profile and
store
Args:
profile (str):
The firewall profile to configure. Valid options are:
- domain
- public
- private
inbound (str):
The inbound setting. If ``None`` is passed, the setting will remain
unchanged. Valid values are:
- blockinbound
- blockinboundalways
- allowinbound
- notconfigured
Default is ``None``
outbound (str):
The outbound setting. If ``None`` is passed, the setting will remain
unchanged. Valid values are:
- allowoutbound
- blockoutbound
- notconfigured
Default is ``None``
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
bool: ``True`` if successful
Raises:
CommandExecutionError: If an error occurs
ValueError: If the parameters are incorrect
'''
# Input validation
if profile.lower() not in ('domain', 'public', 'private'):
raise ValueError('Incorrect profile: {0}'.format(profile))
if inbound and inbound.lower() not in ('blockinbound',
'blockinboundalways',
'allowinbound',
'notconfigured'):
raise ValueError('Incorrect inbound value: {0}'.format(inbound))
if outbound and outbound.lower() not in ('allowoutbound',
'blockoutbound',
'notconfigured'):
raise ValueError('Incorrect outbound value: {0}'.format(outbound))
if not inbound and not outbound:
raise ValueError('Must set inbound or outbound')
# You have to specify inbound and outbound setting at the same time
# If you're only specifying one, you have to get the current setting for the
# other
if not inbound or not outbound:
ret = get_settings(profile=profile,
section='firewallpolicy',
store=store)
if not inbound:
inbound = ret['Inbound']
if not outbound:
outbound = ret['Outbound']
command = 'set {0}profile firewallpolicy {1},{2}' \
''.format(profile, inbound, outbound)
results = _netsh_command(command=command, store=store)
if results:
raise CommandExecutionError('An error occurred: {0}'.format(results))
return True
def set_logging_settings(profile, setting, value, store='local'):
'''
Configure logging settings for the Windows firewall.
Args:
profile (str):
The firewall profile to configure. Valid options are:
- domain
- public
- private
setting (str):
The logging setting to configure. Valid options are:
- allowedconnections
- droppedconnections
- filename
- maxfilesize
value (str):
The value to apply to the setting. Valid values are dependent upon
the setting being configured. Valid options are:
allowedconnections:
- enable
- disable
- notconfigured
droppedconnections:
- enable
- disable
- notconfigured
filename:
- Full path and name of the firewall log file
- notconfigured
maxfilesize:
- 1 - 32767 (Kb)
- notconfigured
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
bool: ``True`` if successful
Raises:
CommandExecutionError: If an error occurs
ValueError: If the parameters are incorrect
'''
# Input validation
if profile.lower() not in ('domain', 'public', 'private'):
raise ValueError('Incorrect profile: {0}'.format(profile))
if setting.lower() not in ('allowedconnections',
'droppedconnections',
'filename',
'maxfilesize'):
raise ValueError('Incorrect setting: {0}'.format(setting))
if setting.lower() in ('allowedconnections', 'droppedconnections'):
if value.lower() not in ('enable', 'disable', 'notconfigured'):
raise ValueError('Incorrect value: {0}'.format(value))
# TODO: Consider adding something like the following to validate filename
# https://stackoverflow.com/questions/9532499/check-whether-a-path-is-valid-in-python-without-creating-a-file-at-the-paths-ta
if setting.lower() == 'maxfilesize':
if value.lower() != 'notconfigured':
# Must be a number between 1 and 32767
try:
int(value)
except ValueError:
raise ValueError('Incorrect value: {0}'.format(value))
if not 1 <= int(value) <= 32767:
raise ValueError('Incorrect value: {0}'.format(value))
# Run the command
command = 'set {0}profile logging {1} {2}'.format(profile, setting, value)
results = _netsh_command(command=command, store=store)
# A successful run should return an empty list
if results:
raise CommandExecutionError('An error occurred: {0}'.format(results))
return True
def set_settings(profile, setting, value, store='local'):
'''
Configure firewall settings.
Args:
profile (str):
The firewall profile to configure. Valid options are:
- domain
- public
- private
setting (str):
The firewall setting to configure. Valid options are:
- localfirewallrules
- localconsecrules
- inboundusernotification
- remotemanagement
- unicastresponsetomulticast
value (str):
The value to apply to the setting. Valid options are
- enable
- disable
- notconfigured
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
bool: ``True`` if successful
Raises:
CommandExecutionError: If an error occurs
ValueError: If the parameters are incorrect
'''
# Input validation
if profile.lower() not in ('domain', 'public', 'private'):
raise ValueError('Incorrect profile: {0}'.format(profile))
if setting.lower() not in ('localfirewallrules',
'localconsecrules',
'inboundusernotification',
'remotemanagement',
'unicastresponsetomulticast'):
raise ValueError('Incorrect setting: {0}'.format(setting))
if value.lower() not in ('enable', 'disable', 'notconfigured'):
raise ValueError('Incorrect value: {0}'.format(value))
# Run the command
command = 'set {0}profile settings {1} {2}'.format(profile, setting, value)
results = _netsh_command(command=command, store=store)
# A successful run should return an empty list
if results:
raise CommandExecutionError('An error occurred: {0}'.format(results))
return True
def set_state(profile, state, store='local'):
'''
Configure the firewall state.
Args:
profile (str):
The firewall profile to configure. Valid options are:
- domain
- public
- private
state (str):
The firewall state. Valid options are:
- on
- off
- notconfigured
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
bool: ``True`` if successful
Raises:
CommandExecutionError: If an error occurs
ValueError: If the parameters are incorrect
'''
# Input validation
if profile.lower() not in ('domain', 'public', 'private'):
raise ValueError('Incorrect profile: {0}'.format(profile))
if state.lower() not in ('on', 'off', 'notconfigured'):
raise ValueError('Incorrect state: {0}'.format(state))
# Run the command
command = 'set {0}profile state {1}'.format(profile, state)
results = _netsh_command(command=command, store=store)
# A successful run should return an empty list
if results:
raise CommandExecutionError('An error occurred: {0}'.format(results))
return True

View file

@ -0,0 +1,535 @@
# -*- coding: utf-8 -*-
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
# Import Salt Testing Libs
from tests.support.helpers import destructiveTest
from tests.support.mock import NO_MOCK, NO_MOCK_REASON
from tests.support.unit import TestCase, skipIf
# Import Salt Libs
import salt.utils.platform
import salt.utils.win_lgpo_netsh as win_lgpo_netsh
from salt.exceptions import CommandExecutionError
@skipIf(NO_MOCK, NO_MOCK_REASON)
@skipIf(not salt.utils.platform.is_windows(), 'System is not Windows')
class WinLgpoNetshTestCase(TestCase):
def test_get_settings_firewallpolicy_local(self):
ret = win_lgpo_netsh.get_settings(profile='domain',
section='firewallpolicy',
store='local')
self.assertIn('Inbound', ret)
self.assertIn('Outbound', ret)
def test_get_settings_firewallpolicy_lgpo(self):
ret = win_lgpo_netsh.get_settings(profile='domain',
section='firewallpolicy',
store='lgpo')
self.assertIn('Inbound', ret)
self.assertIn('Outbound', ret)
def test_get_settings_logging_local(self):
ret = win_lgpo_netsh.get_settings(profile='domain',
section='logging',
store='local')
self.assertIn('FileName', ret)
self.assertIn('LogAllowedConnections', ret)
self.assertIn('LogDroppedConnections', ret)
self.assertIn('MaxFileSize', ret)
def test_get_settings_logging_lgpo(self):
ret = win_lgpo_netsh.get_settings(profile='domain',
section='logging',
store='lgpo')
self.assertIn('FileName', ret)
self.assertIn('LogAllowedConnections', ret)
self.assertIn('LogDroppedConnections', ret)
self.assertIn('MaxFileSize', ret)
def test_get_settings_settings_local(self):
ret = win_lgpo_netsh.get_settings(profile='domain',
section='settings',
store='local')
self.assertIn('InboundUserNotification', ret)
self.assertIn('LocalConSecRules', ret)
self.assertIn('LocalFirewallRules', ret)
self.assertIn('RemoteManagement', ret)
self.assertIn('UnicastResponseToMulticast', ret)
def test_get_settings_settings_lgpo(self):
ret = win_lgpo_netsh.get_settings(profile='domain',
section='settings',
store='lgpo')
self.assertIn('InboundUserNotification', ret)
self.assertIn('LocalConSecRules', ret)
self.assertIn('LocalFirewallRules', ret)
self.assertIn('RemoteManagement', ret)
self.assertIn('UnicastResponseToMulticast', ret)
def test_get_settings_state_local(self):
ret = win_lgpo_netsh.get_settings(profile='domain',
section='state',
store='local')
self.assertIn('State', ret)
def test_get_settings_state_lgpo(self):
ret = win_lgpo_netsh.get_settings(profile='domain',
section='state',
store='lgpo')
self.assertIn('State', ret)
def test_get_all_settings_local(self):
ret = win_lgpo_netsh.get_all_settings(profile='domain',
store='local')
self.assertIn('Inbound', ret)
self.assertIn('Outbound', ret)
self.assertIn('FileName', ret)
self.assertIn('LogAllowedConnections', ret)
self.assertIn('LogDroppedConnections', ret)
self.assertIn('MaxFileSize', ret)
self.assertIn('InboundUserNotification', ret)
self.assertIn('LocalConSecRules', ret)
self.assertIn('LocalFirewallRules', ret)
self.assertIn('RemoteManagement', ret)
self.assertIn('UnicastResponseToMulticast', ret)
self.assertIn('State', ret)
def test_get_all_settings_lgpo(self):
ret = win_lgpo_netsh.get_all_settings(profile='domain',
store='local')
self.assertIn('Inbound', ret)
self.assertIn('Outbound', ret)
self.assertIn('FileName', ret)
self.assertIn('LogAllowedConnections', ret)
self.assertIn('LogDroppedConnections', ret)
self.assertIn('MaxFileSize', ret)
self.assertIn('InboundUserNotification', ret)
self.assertIn('LocalConSecRules', ret)
self.assertIn('LocalFirewallRules', ret)
self.assertIn('RemoteManagement', ret)
self.assertIn('UnicastResponseToMulticast', ret)
self.assertIn('State', ret)
def test_get_all_profiles_local(self):
ret = win_lgpo_netsh.get_all_profiles(store='local')
self.assertIn('Domain Profile', ret)
self.assertIn('Private Profile', ret)
self.assertIn('Public Profile', ret)
def test_get_all_profiles_lgpo(self):
ret = win_lgpo_netsh.get_all_profiles(store='lgpo')
self.assertIn('Domain Profile', ret)
self.assertIn('Private Profile', ret)
self.assertIn('Public Profile', ret)
@destructiveTest
def test_set_firewall_settings_inbound_local(self):
current = win_lgpo_netsh.get_settings(profile='domain',
section='firewallpolicy',
store='local')['Inbound']
try:
ret = win_lgpo_netsh.set_firewall_settings(profile='domain',
inbound='allowinbound',
store='local')
self.assertTrue(ret)
new = win_lgpo_netsh.get_settings(profile='domain',
section='firewallpolicy',
store='local')['Inbound']
self.assertEqual('AllowInbound', new)
finally:
ret = win_lgpo_netsh.set_firewall_settings(profile='domain',
inbound=current,
store='local')
self.assertTrue(ret)
@destructiveTest
def test_set_firewall_settings_inbound_local_notconfigured(self):
current = win_lgpo_netsh.get_settings(profile='domain',
section='firewallpolicy',
store='local')['Inbound']
try:
self.assertRaises(
CommandExecutionError,
win_lgpo_netsh.set_firewall_settings,
profile='domain',
inbound='notconfigured',
store='local')
finally:
ret = win_lgpo_netsh.set_firewall_settings(profile='domain',
inbound=current,
store='local')
self.assertTrue(ret)
@destructiveTest
def test_set_firewall_settings_inbound_lgpo_notconfigured(self):
current = win_lgpo_netsh.get_settings(profile='domain',
section='firewallpolicy',
store='lgpo')['Inbound']
try:
ret = win_lgpo_netsh.set_firewall_settings(profile='domain',
inbound='notconfigured',
store='lgpo')
self.assertTrue(ret)
new = win_lgpo_netsh.get_settings(profile='domain',
section='firewallpolicy',
store='lgpo')['Inbound']
self.assertEqual('NotConfigured', new)
finally:
ret = win_lgpo_netsh.set_firewall_settings(profile='domain',
inbound=current,
store='lgpo')
self.assertTrue(ret)
@destructiveTest
def test_set_firewall_settings_outbound_local(self):
current = win_lgpo_netsh.get_settings(profile='domain',
section='firewallpolicy',
store='local')['Outbound']
try:
ret = win_lgpo_netsh.set_firewall_settings(profile='domain',
outbound='allowoutbound',
store='local')
self.assertTrue(ret)
new = win_lgpo_netsh.get_settings(profile='domain',
section='firewallpolicy',
store='local')['Outbound']
self.assertEqual('AllowOutbound', new)
finally:
ret = win_lgpo_netsh.set_firewall_settings(profile='domain',
outbound=current,
store='local')
self.assertTrue(ret)
@destructiveTest
def test_set_firewall_logging_allowed_local_enable(self):
current = win_lgpo_netsh.get_settings(profile='domain',
section='logging',
store='local')['LogAllowedConnections']
try:
ret = win_lgpo_netsh.set_logging_settings(profile='domain',
setting='allowedconnections',
value='enable',
store='local')
self.assertTrue(ret)
new = win_lgpo_netsh.get_settings(profile='domain',
section='logging',
store='local')['LogAllowedConnections']
self.assertEqual('Enable', new)
finally:
ret = win_lgpo_netsh.set_logging_settings(profile='domain',
setting='allowedconnections',
value=current,
store='local')
self.assertTrue(ret)
@destructiveTest
def test_set_firewall_logging_allowed_local_notconfigured(self):
current = win_lgpo_netsh.get_settings(profile='domain',
section='logging',
store='local')['LogAllowedConnections']
try:
self.assertRaises(
CommandExecutionError,
win_lgpo_netsh.set_logging_settings,
profile='domain',
setting='allowedconnections',
value='notconfigured',
store='local')
finally:
ret = win_lgpo_netsh.set_logging_settings(profile='domain',
setting='allowedconnections',
value=current,
store='local')
self.assertTrue(ret)
@destructiveTest
def test_set_firewall_logging_allowed_lgpo_notconfigured(self):
current = win_lgpo_netsh.get_settings(profile='domain',
section='logging',
store='lgpo')['LogAllowedConnections']
try:
ret = win_lgpo_netsh.set_logging_settings(profile='domain',
setting='allowedconnections',
value='notconfigured',
store='lgpo')
self.assertTrue(ret)
new = win_lgpo_netsh.get_settings(profile='domain',
section='logging',
store='lgpo')['LogAllowedConnections']
self.assertEqual('NotConfigured', new)
finally:
ret = win_lgpo_netsh.set_logging_settings(profile='domain',
setting='allowedconnections',
value=current,
store='lgpo')
self.assertTrue(ret)
def test_set_firewall_logging_dropped_local_enable(self):
current = win_lgpo_netsh.get_settings(profile='domain',
section='logging',
store='local')['LogDroppedConnections']
try:
ret = win_lgpo_netsh.set_logging_settings(profile='domain',
setting='droppedconnections',
value='enable',
store='local')
self.assertTrue(ret)
new = win_lgpo_netsh.get_settings(profile='domain',
section='logging',
store='local')['LogDroppedConnections']
self.assertEqual('Enable', new)
finally:
ret = win_lgpo_netsh.set_logging_settings(profile='domain',
setting='droppedconnections',
value=current,
store='local')
self.assertTrue(ret)
def test_set_firewall_logging_filename_local(self):
current = win_lgpo_netsh.get_settings(profile='domain',
section='logging',
store='local')['FileName']
try:
ret = win_lgpo_netsh.set_logging_settings(profile='domain',
setting='filename',
value='C:\\Temp\\test.log',
store='local')
self.assertTrue(ret)
new = win_lgpo_netsh.get_settings(profile='domain',
section='logging',
store='local')['FileName']
self.assertEqual('C:\\Temp\\test.log', new)
finally:
ret = win_lgpo_netsh.set_logging_settings(profile='domain',
setting='filename',
value=current,
store='local')
self.assertTrue(ret)
def test_set_firewall_logging_maxfilesize_local(self):
current = win_lgpo_netsh.get_settings(profile='domain',
section='logging',
store='local')['MaxFileSize']
try:
ret = win_lgpo_netsh.set_logging_settings(profile='domain',
setting='maxfilesize',
value='16384',
store='local')
self.assertTrue(ret)
new = win_lgpo_netsh.get_settings(profile='domain',
section='logging',
store='local')['MaxFileSize']
self.assertEqual('16384', new)
finally:
ret = win_lgpo_netsh.set_logging_settings(profile='domain',
setting='maxfilesize',
value=current,
store='local')
self.assertTrue(ret)
@destructiveTest
def test_set_firewall_settings_fwrules_local_enable(self):
self.assertRaises(
win_lgpo_netsh.set_settings,
profile='domain',
setting='localfirewallrules',
value='enable',
store='local')
@destructiveTest
def test_set_firewall_settings_fwrules_lgpo_notconfigured(self):
current = win_lgpo_netsh.get_settings(profile='domain',
section='settings',
store='lgpo')['LocalFirewallRules']
try:
ret = win_lgpo_netsh.set_settings(profile='domain',
setting='localfirewallrules',
value='notconfigured',
store='lgpo')
self.assertTrue(ret)
new = win_lgpo_netsh.get_settings(profile='domain',
section='settings',
store='lgpo')['LocalFirewallRules']
self.assertEqual('NotConfigured', new)
finally:
ret = win_lgpo_netsh.set_settings(profile='domain',
setting='localfirewallrules',
value=current,
store='lgpo')
self.assertTrue(ret)
@destructiveTest
def test_set_firewall_settings_consecrules_local_enable(self):
self.assertRaises(
win_lgpo_netsh.set_settings,
profile='domain',
setting='localconsecrules',
value='enable',
store='local')
def test_set_firewall_settings_notification_local_enable(self):
current = win_lgpo_netsh.get_settings(profile='domain',
section='settings',
store='local')['InboundUserNotification']
try:
ret = win_lgpo_netsh.set_settings(profile='domain',
setting='inboundusernotification',
value='enable',
store='local')
self.assertTrue(ret)
new = win_lgpo_netsh.get_settings(profile='domain',
section='settings',
store='local')['InboundUserNotification']
self.assertEqual('Enable', new)
finally:
ret = win_lgpo_netsh.set_settings(profile='domain',
setting='inboundusernotification',
value=current,
store='local')
self.assertTrue(ret)
@destructiveTest
def test_set_firewall_settings_notification_local_notconfigured(self):
current = win_lgpo_netsh.get_settings(profile='domain',
section='settings',
store='local')['InboundUserNotification']
try:
self.assertRaises(
CommandExecutionError,
win_lgpo_netsh.set_settings,
profile='domain',
setting='inboundusernotification',
value='notconfigured',
store='local')
finally:
ret = win_lgpo_netsh.set_settings(profile='domain',
setting='inboundusernotification',
value=current,
store='local')
self.assertTrue(ret)
def test_set_firewall_settings_notification_lgpo_notconfigured(self):
current = win_lgpo_netsh.get_settings(profile='domain',
section='settings',
store='lgpo')['InboundUserNotification']
try:
ret = win_lgpo_netsh.set_settings(profile='domain',
setting='inboundusernotification',
value='notconfigured',
store='lgpo')
self.assertTrue(ret)
new = win_lgpo_netsh.get_settings(profile='domain',
section='settings',
store='lgpo')['InboundUserNotification']
self.assertEqual('NotConfigured', new)
finally:
ret = win_lgpo_netsh.set_settings(profile='domain',
setting='inboundusernotification',
value=current,
store='lgpo')
self.assertTrue(ret)
def test_set_firewall_settings_remotemgmt_local_enable(self):
current = win_lgpo_netsh.get_settings(profile='domain',
section='settings',
store='local')['RemoteManagement']
try:
ret = win_lgpo_netsh.set_settings(profile='domain',
setting='remotemanagement',
value='enable',
store='local')
self.assertTrue(ret)
new = win_lgpo_netsh.get_settings(profile='domain',
section='settings',
store='local')['RemoteManagement']
self.assertEqual('Enable', new)
finally:
ret = win_lgpo_netsh.set_settings(profile='domain',
setting='remotemanagement',
value=current,
store='local')
self.assertTrue(ret)
def test_set_firewall_settings_unicast_local_disable(self):
current = win_lgpo_netsh.get_settings(profile='domain',
section='settings',
store='local')['UnicastResponseToMulticast']
try:
ret = win_lgpo_netsh.set_settings(profile='domain',
setting='unicastresponsetomulticast',
value='disable',
store='local')
self.assertTrue(ret)
new = win_lgpo_netsh.get_settings(profile='domain',
section='settings',
store='local')['UnicastResponseToMulticast']
self.assertEqual('Disable', new)
finally:
ret = win_lgpo_netsh.set_settings(profile='domain',
setting='unicastresponsetomulticast',
value=current,
store='local')
self.assertTrue(ret)
@destructiveTest
def test_set_firewall_state_local_on(self):
current = win_lgpo_netsh.get_settings(profile='domain',
section='state',
store='local')['State']
try:
ret = win_lgpo_netsh.set_state(profile='domain',
state='off',
store='local')
self.assertTrue(ret)
new = win_lgpo_netsh.get_settings(profile='domain',
section='state',
store='local')['State']
self.assertEqual('OFF', new)
finally:
ret = win_lgpo_netsh.set_state(profile='domain',
state=current,
store='local')
self.assertTrue(ret)
@destructiveTest
def test_set_firewall_state_local_notconfigured(self):
current = win_lgpo_netsh.get_settings(profile='domain',
section='state',
store='local')['State']
try:
self.assertRaises(
CommandExecutionError,
win_lgpo_netsh.set_state,
profile='domain',
state='notconfigured',
store='local')
finally:
ret = win_lgpo_netsh.set_state(profile='domain',
state=current,
store='local')
self.assertTrue(ret)
@destructiveTest
def test_set_firewall_state_lgpo_notconfigured(self):
current = win_lgpo_netsh.get_settings(profile='domain',
section='state',
store='local')['State']
try:
ret = win_lgpo_netsh.set_state(profile='domain',
state='notconfigured',
store='lgpo')
self.assertTrue(ret)
new = win_lgpo_netsh.get_settings(profile='domain',
section='state',
store='lgpo')['State']
self.assertEqual('NotConfigured', new)
finally:
ret = win_lgpo_netsh.set_state(profile='domain',
state=current,
store='lgpo')
self.assertTrue(ret)