Merge branch 'master' into salt-check-fullmerge

This commit is contained in:
Daniel Wozniak 2020-01-05 18:09:18 -07:00 committed by GitHub
commit 5e0cfeb347
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
16 changed files with 2724 additions and 1211 deletions

1
.gitignore vendored
View file

@ -106,6 +106,7 @@ tests/integration/cloud/providers/pki/minions
# Kitchen tests files
.kitchen.local.yml
kitchen.local.yml
.kitchen/
.bundle/
Gemfile.lock

View file

@ -536,7 +536,10 @@ class Client(object):
if url_data.scheme == 'ftp':
try:
ftp = ftplib.FTP()
ftp.connect(url_data.hostname, url_data.port)
ftp_port = url_data.port
if not ftp_port:
ftp_port = 21
ftp.connect(url_data.hostname, ftp_port)
ftp.login(url_data.username, url_data.password)
remote_file_path = url_data.path.lstrip('/')
with salt.utils.files.fopen(dest, 'wb') as fp_:

View file

@ -18,6 +18,9 @@ import os
import re
import logging
import time
import fnmatch
import datetime
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
@ -384,6 +387,7 @@ def install(name=None,
pkgs=None,
sources=None,
reinstall=False,
downloadonly=False,
ignore_epoch=False,
**kwargs):
'''
@ -730,6 +734,9 @@ def install(name=None,
cmd.extend(downgrade)
cmds.append(cmd)
if downloadonly:
cmd.append("--download-only")
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
@ -2846,3 +2853,37 @@ def _get_http_proxy_url():
)
return http_proxy_url
def list_downloaded(root=None, **kwargs):
'''
.. versionadded:: 3000?
List prefetched packages downloaded by apt in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/apt'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.deb'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret

File diff suppressed because it is too large Load diff

View file

@ -200,7 +200,7 @@ def until_no_eval(
current_attempt += 1
try:
res = __salt__[name](*args, **kwargs)
except Exception:
except Exception: # pylint: disable=broad-except
(exc_type, exc_value, _) = sys.exc_info()
ret['comment'] = 'Exception occurred while executing {}: {}:{}'.format(name, exc_type, exc_value)
break

View file

@ -2035,7 +2035,7 @@ def downloaded(name,
(if specified).
Currently supported for the following pkg providers:
:mod:`yumpkg <salt.modules.yumpkg>` and :mod:`zypper <salt.modules.zypper>`
:mod:`yumpkg <salt.modules.yumpkg>`, :mod:`zypper <salt.modules.zypper>` and :mod:`zypper <salt.modules.aptpkg>`
:param str name:
The name of the package to be downloaded. This parameter is ignored if
@ -2174,7 +2174,7 @@ def downloaded(name,
if not ret['changes'] and not ret['comment']:
ret['result'] = True
ret['comment'] = 'Packages are already downloaded: ' \
ret['comment'] = 'Packages downloaded: ' \
'{0}'.format(', '.join(targets))
return ret

View file

@ -7,9 +7,11 @@ Manage Windows Local Group Policy
This state allows configuring local Windows Group Policy
The state can be used to ensure the setting of a single policy or multiple policies in one pass.
The state can be used to ensure the setting of a single policy or multiple
policies in one pass.
Single policies must specify the policy name, the setting, and the policy class (Machine/User/Both)
Single policies must specify the policy name, the setting, and the policy class
(Machine/User/Both)
Example single policy configuration
@ -24,7 +26,7 @@ Example single policy configuration
.. code-block:: yaml
Account lockout duration:
gpo.set:
lgpo.set:
- setting: 120
- policy_class: Machine
@ -35,10 +37,11 @@ Multiple policy configuration
Company Local Group Policy:
lgpo.set:
- computer_policy:
Deny logon locally: Guest
Deny log on locally:
- Guest
Account lockout duration: 120
Account lockout threshold: 10
Reset account lockout counter after: 1440
Reset account lockout counter after: 120
Enforce password history: 24
Maximum password age: 60
Minimum password age: 1
@ -63,9 +66,9 @@ Multiple policy configuration
Maximum password age: 60
Minimum password age: 1
Minimum password length: 14
Account lockout duration: 1440
Account lockout duration: 120
Account lockout threshold: 10
Reset account lockout counter after: 1440
Reset account lockout counter after: 120
Manage auditing and security log:
- "BUILTIN\\Administrators"
Replace a process level token:
@ -100,9 +103,7 @@ Multiple policy configuration
"Set the intranet update service for detecting updates": http://mywsus
"Set the intranet statistics server": http://mywsus
- cumulative_rights_assignments: True
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
@ -111,6 +112,7 @@ import logging
import salt.utils.data
import salt.utils.dictdiffer
import salt.utils.json
import salt.utils.win_functions
# Import 3rd party libs
from salt.ext import six
@ -133,7 +135,7 @@ def _compare_policies(new_policy, current_policy):
otherwise ``False``
'''
# Compared dicts, lists, and strings
if isinstance(new_policy, six.string_types):
if isinstance(new_policy, (six.string_types, six.integer_types)):
return new_policy == current_policy
elif isinstance(new_policy, list):
if isinstance(current_policy, list):
@ -157,54 +159,69 @@ def set_(name,
cumulative_rights_assignments=True,
adml_language='en-US'):
'''
Ensure the specified policy is set
Ensure the specified policy is set.
name
the name of a single policy to configure
.. warning::
The ``setting`` argument cannot be used in conjunction with the
``computer_policy`` or ``user_policy`` arguments
setting
the configuration setting for the single named policy
if this argument is used the computer_policy/user_policy arguments will be ignored
Args:
name (str): The name of a single policy to configure
policy_class
the policy class of the single named policy to configure
this can "machine", "user", or "both"
setting (str, dict, list):
The configuration setting for the single named policy. If this
argument is used the ``computer_policy`` / ``user_policy`` arguments
will be ignored
computer_policy
a dict of policyname: value pairs of a set of computer policies to configure
if this argument is used, the name/setting/policy_class arguments will be ignored
policy_class (str):
The policy class of the single named policy to configure. This can
``machine``, ``user``, or ``both``
user_policy
a dict of policyname: value pairs of a set of user policies to configure
if this argument is used, the name/setting/policy_class arguments will be ignored
computer_policy (dict):
A dictionary of containing the policy name and key/value pairs of a
set of computer policies to configure. If this argument is used, the
``name`` / ``policy_class`` arguments will be ignored
cumulative_rights_assignments
determine if any user right assignment policies specified will be cumulative
or explicit
user_policy (dict):
A dictionary of containing the policy name and key/value pairs of a
set of user policies to configure. If this argument is used, the
``name`` / ``policy_class`` arguments will be ignored
adml_language
the adml language to use for AMDX policy data/display conversions
cumulative_rights_assignments (bool):
If user rights assignments are being configured, determines if any
user right assignment policies specified will be cumulative or
explicit
adml_language (str):
The adml language to use for AMDX policy data/display conversions.
Default is ``en-US``
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
policy_classes = ['machine', 'computer', 'user', 'both']
class_map = {
'computer': 'Computer Configuration',
'machine': 'Computer Configuration',
'user': 'User Configuration'
}
if not setting and not computer_policy and not user_policy:
msg = 'At least one of the parameters setting, computer_policy, or user_policy'
msg = msg + ' must be specified.'
msg = 'At least one of the parameters setting, computer_policy, or ' \
'user_policy must be specified.'
ret['result'] = False
ret['comment'] = msg
return ret
if setting and not policy_class:
msg = 'A single policy setting was specified but the policy_class was not specified.'
msg = 'A single policy setting was specified but the policy_class ' \
'was not specified.'
ret['result'] = False
ret['comment'] = msg
return ret
if setting and (computer_policy or user_policy):
msg = 'The setting and computer_policy/user_policy parameters are mutually exclusive. Please'
msg = msg + ' specify either a policy name and setting or a computer_policy and/or user_policy'
msg = msg + ' dict'
msg = 'The setting and computer_policy/user_policy parameters are ' \
'mutually exclusive. Please specify either a policy name and ' \
'setting or a computer_policy and/or user_policy dict'
ret['result'] = False
ret['comment'] = msg
return ret
@ -238,68 +255,62 @@ def set_(name,
computer_policy[name] = setting
elif policy_class.lower() == 'user':
user_policy[name] = setting
elif policy_class.lower() == 'machine' or policy_class.lower() == 'computer':
elif policy_class.lower() in ['machine', 'computer']:
computer_policy[name] = setting
pol_data = {}
pol_data['user'] = {'output_section': 'User Configuration',
'requested_policy': user_policy,
'policy_lookup': {}}
pol_data['machine'] = {'output_section': 'Computer Configuration',
'requested_policy': computer_policy,
'policy_lookup': {}}
pol_data = {
'user': {
'requested_policy': user_policy,
'policy_lookup': {}},
'machine': {
'requested_policy': computer_policy,
'policy_lookup': {}}}
current_policy = {}
for p_class, p_data in six.iteritems(pol_data):
if p_data['requested_policy']:
for policy_name, policy_setting in six.iteritems(p_data['requested_policy']):
lookup = __salt__['lgpo.get_policy_info'](policy_name,
p_class,
adml_language=adml_language)
for p_name, _ in six.iteritems(p_data['requested_policy']):
lookup = __salt__['lgpo.get_policy_info'](
policy_name=p_name,
policy_class=p_class,
adml_language=adml_language)
if lookup['policy_found']:
pol_data[p_class]['policy_lookup'][policy_name] = lookup
pol_data[p_class]['policy_lookup'][p_name] = lookup
# Since we found the policy, let's get the current setting
# as well
current_policy.setdefault(class_map[p_class], {})
current_policy[class_map[p_class]][p_name] = __salt__['lgpo.get_policy'](
policy_name=p_name,
policy_class=p_class,
adml_language=adml_language,
return_value_only=True)
else:
ret['comment'] = ' '.join([ret['comment'], lookup['message']])
ret['result'] = False
if not ret['result']:
return ret
current_policy = __salt__['lgpo.get'](policy_class=policy_class,
adml_language=adml_language,
hierarchical_return=False)
log.debug('pol_data == %s', pol_data)
log.debug('current policy == %s', current_policy)
# compare policies
policy_changes = []
for policy_section, policy_data in six.iteritems(pol_data):
pol_id = None
if policy_data and policy_data['output_section'] in current_policy:
for policy_name, policy_setting in six.iteritems(policy_data['requested_policy']):
currently_set = False
# Check Case sensitive first (faster)
if policy_name in current_policy[policy_data['output_section']]:
for p_class, p_data in six.iteritems(pol_data):
requested_policy = p_data.get('requested_policy')
if requested_policy:
for p_name, p_setting in six.iteritems(requested_policy):
if p_name in current_policy[class_map[p_class]]:
currently_set = True
pol_id = policy_name
# Check case insensitive
elif policy_name.lower() in (k.lower() for k in current_policy[policy_data['output_section']]):
for p_name in current_policy[policy_data['output_section']]:
if policy_name.lower() == p_name.lower():
currently_set = True
pol_id = p_name
break
# Check aliases
else:
for alias in policy_data['policy_lookup'][policy_name]['policy_aliases']:
log.debug('checking alias %s', alias)
if alias in current_policy[policy_data['output_section']]:
currently_set = True
pol_id = alias
break
if currently_set:
# compare
log.debug('need to compare %s from '
'current/requested policy', policy_name)
log.debug('need to compare %s from current/requested '
'policy', p_name)
changes = False
requested_policy_json = salt.utils.json.dumps(policy_data['requested_policy'][policy_name], sort_keys=True).lower()
current_policy_json = salt.utils.json.dumps(current_policy[policy_data['output_section']][pol_id], sort_keys=True).lower()
requested_policy_json = salt.utils.json.dumps(
p_data['requested_policy'][p_name],
sort_keys=True).lower()
current_policy_json = salt.utils.json.dumps(
current_policy[class_map[p_class]][p_name],
sort_keys=True).lower()
requested_policy_check = salt.utils.json.loads(requested_policy_json)
current_policy_check = salt.utils.json.loads(current_policy_json)
@ -310,35 +321,39 @@ def set_(name,
if not policies_are_equal:
additional_policy_comments = []
if policy_data['policy_lookup'][policy_name]['rights_assignment'] and cumulative_rights_assignments:
for user in policy_data['requested_policy'][policy_name]:
if user not in current_policy[policy_data['output_section']][pol_id]:
changes = True
if p_data['policy_lookup'][p_name]['rights_assignment'] and cumulative_rights_assignments:
for user in p_data['requested_policy'][p_name]:
if user not in current_policy[class_map[p_class]][p_name]:
user = salt.utils.win_functions.get_sam_name(user)
if user not in current_policy[class_map[p_class]][p_name]:
changes = True
else:
additional_policy_comments.append('"{0}" is already granted the right'.format(user))
else:
additional_policy_comments.append('"{0}" is already granted the right'.format(user))
else:
changes = True
if changes:
log.debug('%s current policy != requested policy',
policy_name)
p_name)
log.debug(
'we compared %s to %s',
requested_policy_json, current_policy_json
)
policy_changes.append(policy_name)
policy_changes.append(p_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(p_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(p_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']
'the requested setting', p_name)
ret['comment'] = '"{0}" is already set\n'.format(p_name) + ret['comment']
else:
policy_changes.append(policy_name)
policy_changes.append(p_name)
log.debug('policy %s is not set, we will configure it',
policy_name)
p_name)
if __opts__['test']:
if policy_changes:
ret['result'] = None
@ -348,17 +363,26 @@ def set_(name,
ret['comment'] = 'All specified policies are properly configured'
else:
if policy_changes:
_ret = __salt__['lgpo.set'](computer_policy=computer_policy,
user_policy=user_policy,
cumulative_rights_assignments=cumulative_rights_assignments,
adml_language=adml_language)
_ret = __salt__['lgpo.set'](
computer_policy=computer_policy,
user_policy=user_policy,
cumulative_rights_assignments=cumulative_rights_assignments,
adml_language=adml_language)
if _ret:
ret['result'] = _ret
new_policy = {}
for p_class, p_data in six.iteritems(pol_data):
if p_data['requested_policy']:
for p_name, p_setting in six.iteritems(
p_data['requested_policy']):
new_policy.setdefault(class_map[p_class], {})
new_policy[class_map[p_class]][p_name] = __salt__['lgpo.get_policy'](
policy_name=p_name,
policy_class=p_class,
adml_language=adml_language,
return_value_only=True)
ret['changes'] = salt.utils.dictdiffer.deep_diff(
current_policy,
__salt__['lgpo.get'](policy_class=policy_class,
adml_language=adml_language,
hierarchical_return=False))
old=current_policy, new=new_policy)
if ret['changes']:
ret['comment'] = 'The following policies changed:\n{0}' \
''.format('\n'.join(policy_changes))

View file

@ -122,8 +122,6 @@ def wrap_tmpl_func(render_str):
slspath = context['sls'].replace('.', '/')
if tmplpath is not None:
context['tplpath'] = tmplpath
if not tmplpath.lower().replace('\\', '/').endswith('/init.sls'):
slspath = os.path.dirname(slspath)
template = tmplpath.replace('\\', '/')
i = template.rfind(slspath.replace('.', '/'))
if i != -1:

View file

@ -89,6 +89,8 @@ def _to_unicode(vdata):
# None does not convert to Unicode
if vdata is None:
return None
if isinstance(vdata, int):
vdata = str(vdata)
return salt.utils.stringutils.to_unicode(vdata, 'utf-8')
@ -522,7 +524,7 @@ def read_value(hive, key, vname=None, use_32bit_registry=False):
try:
# RegQueryValueEx returns and accepts unicode data
vdata, vtype = win32api.RegQueryValueEx(handle, local_vname)
if vdata or vdata in [0, '']:
if vdata or vdata in [0, '', []]:
# Only convert text types to unicode
ret['vtype'] = registry.vtype_reverse[vtype]
if vtype == win32con.REG_MULTI_SZ:

View file

@ -386,6 +386,21 @@ class CPModuleTest(ModuleCase):
self.assertIn('KNIGHT: They\'re nervous, sire.', ret)
self.assertNotIn('bacon', ret)
@with_tempfile()
def test_get_url_ftp(self, tgt):
'''
cp.get_url with https:// source given
'''
self.run_function(
'cp.get_url',
[
'ftp://ftp.freebsd.org/pub/FreeBSD/releases/amd64/amd64/12.0-RELEASE/MANIFEST',
tgt,
])
with salt.utils.files.fopen(tgt, 'r') as instructions:
data = salt.utils.stringutils.to_unicode(instructions.read())
self.assertIn('Base system', data)
# cp.get_file_str tests
def test_get_file_str_salt(self):

View file

@ -56,15 +56,16 @@ class WinLgpoTest(ModuleCase):
(policy_name, policy_config))
self.assertTrue(ret)
val = reg.read_value(
registry_value_hive,
registry_value_path,
registry_value_vname)
hive=registry_value_hive,
key=registry_value_path,
vname=registry_value_vname)
self.assertTrue(val['success'], msg='Failed to obtain the registry data for policy {0}'.format(policy_name))
if val['success']:
self.assertEqual(val['vdata'], expected_value_data, 'The registry value data {0} does not match the expected value {1} for policy {2}'.format(
val['vdata'],
expected_value_data,
policy_name))
self.assertEqual(
val['vdata'],
expected_value_data,
'The registry value data {0} does not match the expected value {1} for policy {2}'.format(
val['vdata'], expected_value_data, policy_name))
def _testSeceditPolicy(self,
policy_name,
@ -180,12 +181,13 @@ class WinLgpoTest(ModuleCase):
log.debug('Unable to get osrelease grain')
if not os.path.exists(r'c:\windows\system32\lgpo.exe'):
log.debug('lgpo.exe does not exist, attempting to download/extract')
ret = cls().run_function('state.single',
('archive.extracted', r'c:\windows\system32'),
source='https://download.microsoft.com/download/8/5/C/85C25433-A1B0-4FFA-9429-7E023E7DA8D8/LGPO.zip',
archive_format='zip',
source_hash='sha256=6ffb6416366652993c992280e29faea3507b5b5aa661c33ba1af31f48acea9c4',
enforce_toplevel=False)
ret = cls().run_function(
'state.single',
('archive.extracted', r'c:\windows\system32'),
source='https://download.microsoft.com/download/8/5/C/85C25433-A1B0-4FFA-9429-7E023E7DA8D8/LGPO.zip',
archive_format='zip',
source_hash='sha256=6ffb6416366652993c992280e29faea3507b5b5aa661c33ba1af31f48acea9c4',
enforce_toplevel=False)
log.debug('ret from archive.unzip == %s', ret)
@destructiveTest
@ -208,13 +210,13 @@ class WinLgpoTest(ModuleCase):
policy_class='User')
# Enable Point and Print Restrictions
self._testAdmxPolicy(
r'Control Panel\Printers\Point and Print Restrictions',
r'Point and Print Restrictions',
{
'Users can only point and print to these servers': True,
'Enter fully qualified server names separated by semicolons': 'fakeserver1;fakeserver2',
'Users can only point and print to machines in their forest': True,
'Security Prompts: When installing drivers for a new connection': 'Show warning and elevation prompt',
'When updating drivers for an existing connection': 'Do not show warning or elevation prompt',
'When updating drivers for an existing connection': 'Show warning only',
},
[
r'User[\s]*Software\\Policies\\Microsoft\\Windows NT\\Printers\\PointAndPrint[\s]*Restricted[\s]*DWORD:1',
@ -222,15 +224,14 @@ class WinLgpoTest(ModuleCase):
r'User[\s]*Software\\Policies\\Microsoft\\Windows NT\\Printers\\PointAndPrint[\s]*ServerList[\s]*SZ:fakeserver1;fakeserver2',
r'User[\s]*Software\\Policies\\Microsoft\\Windows NT\\Printers\\PointAndPrint[\s]*InForest[\s]*DWORD:1',
r'User[\s]*Software\\Policies\\Microsoft\\Windows NT\\Printers\\PointAndPrint[\s]*NoWarningNoElevationOnInstall[\s]*DWORD:0',
r'User[\s]*Software\\Policies\\Microsoft\\Windows NT\\Printers\\PointAndPrint[\s]*UpdatePromptSettings[\s]*DWORD:2',
r'User[\s]*Software\\Policies\\Microsoft\\Windows NT\\Printers\\PointAndPrint[\s]*UpdatePromptSettings[\s]*DWORD:1',
],
policy_class='User')
# set Point and Print Restrictions to 'Not Configured'
self._testAdmxPolicy(
r'Control Panel\Printers\Point and Print Restrictions',
'Not Configured',
[
r'; Source file: c:\\windows\\system32\\grouppolicy\\user\\registry.pol[\s]*; PARSING COMPLETED.'],
[r'; Source file: c:\\windows\\system32\\grouppolicy\\user\\registry.pol[\s]*; PARSING COMPLETED.'],
policy_class='User')
@destructiveTest
@ -239,41 +240,44 @@ class WinLgpoTest(ModuleCase):
Test setting/unsetting/changing NTP Client policies
'''
# Disable Configure NTP Client
self._testAdmxPolicy(r'System\Windows Time Service\Time Providers\Configure Windows NTP Client',
'Disabled',
[
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\Parameters[\s]*NtpServer[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\Parameters[\s]*Type[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\TimeProviders\\NtpClient[\s]*CrossSiteSyncFlags[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\TimeProviders\\NtpClient[\s]*ResolvePeerBackoffMinutes[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\TimeProviders\\NtpClient[\s]*ResolvePeerBackoffMaxTimes[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\TimeProviders\\NtpClient[\s]*SpecialPollInterval[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\TimeProviders\\NtpClient[\s]*EventLogFlags[\s]*DELETE'
])
self._testAdmxPolicy(
r'System\Windows Time Service\Time Providers\Configure Windows NTP Client',
'Disabled',
[
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\Parameters[\s]*NtpServer[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\Parameters[\s]*Type[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\TimeProviders\\NtpClient[\s]*CrossSiteSyncFlags[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\TimeProviders\\NtpClient[\s]*ResolvePeerBackoffMinutes[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\TimeProviders\\NtpClient[\s]*ResolvePeerBackoffMaxTimes[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\TimeProviders\\NtpClient[\s]*SpecialPollInterval[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\TimeProviders\\NtpClient[\s]*EventLogFlags[\s]*DELETE'
])
# Enable Configure NTP Client
self._testAdmxPolicy(r'System\Windows Time Service\Time Providers\Configure Windows NTP Client',
{
'NtpServer': 'time.windows.com,0x9',
'Type': 'NT5DS',
'CrossSiteSyncFlags': 2,
'ResolvePeerBackoffMinutes': 15,
'ResolvePeerBackoffMaxTimes': 7,
'W32TIME_SpecialPollInterval': 3600,
'W32TIME_NtpClientEventLogFlags': 0
},
[
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\Parameters[\s]*NtpServer[\s]*SZ:time.windows.com,0x9',
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\Parameters[\s]*Type[\s]*SZ:NT5DS',
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\TimeProviders\\NtpClient[\s]*CrossSiteSyncFlags[\s]*DWORD:2',
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\TimeProviders\\NtpClient[\s]*ResolvePeerBackoffMinutes[\s]*DWORD:15',
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\TimeProviders\\NtpClient[\s]*ResolvePeerBackoffMaxTimes[\s]*DWORD:7',
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\TimeProviders\\NtpClient[\s]*SpecialPollInterval[\s]*DWORD:3600',
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\TimeProviders\\NtpClient[\s]*EventLogFlags[\s]*DWORD:0',
])
self._testAdmxPolicy(
r'System\Windows Time Service\Time Providers\Configure Windows NTP Client',
{
'NtpServer': 'time.windows.com,0x9',
'Type': 'NT5DS',
'CrossSiteSyncFlags': 2,
'ResolvePeerBackoffMinutes': 15,
'ResolvePeerBackoffMaxTimes': 7,
'W32TIME_SpecialPollInterval': 3600,
'W32TIME_NtpClientEventLogFlags': 0
},
[
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\Parameters[\s]*NtpServer[\s]*SZ:time.windows.com,0x9',
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\Parameters[\s]*Type[\s]*SZ:NT5DS',
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\TimeProviders\\NtpClient[\s]*CrossSiteSyncFlags[\s]*DWORD:2',
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\TimeProviders\\NtpClient[\s]*ResolvePeerBackoffMinutes[\s]*DWORD:15',
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\TimeProviders\\NtpClient[\s]*ResolvePeerBackoffMaxTimes[\s]*DWORD:7',
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\TimeProviders\\NtpClient[\s]*SpecialPollInterval[\s]*DWORD:3600',
r'Computer[\s]*Software\\Policies\\Microsoft\\W32time\\TimeProviders\\NtpClient[\s]*EventLogFlags[\s]*DWORD:0',
])
# set Configure NTP Client to 'Not Configured'
self._testAdmxPolicy(r'System\Windows Time Service\Time Providers\Configure Windows NTP Client',
'Not Configured',
[r'; Source file: c:\\windows\\system32\\grouppolicy\\machine\\registry.pol[\s]*; PARSING COMPLETED.'])
self._testAdmxPolicy(
r'System\Windows Time Service\Time Providers\Configure Windows NTP Client',
'Not Configured',
[r'; Source file: c:\\windows\\system32\\grouppolicy\\machine\\registry.pol[\s]*; PARSING COMPLETED.'])
@destructiveTest
def test_set_computer_policy_RA_Unsolicit(self):
@ -283,32 +287,35 @@ class WinLgpoTest(ModuleCase):
# Disable RA_Unsolicit
log.debug('Attempting to disable RA_Unsolicit')
self._testAdmxPolicy('RA_Unsolicit',
'Disabled',
[
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services[\s]*fAllowUnsolicited[\s]*DWORD:0',
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services[\s]*fAllowUnsolicitedFullControl[\s]*DELETE',
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services\\RAUnsolicit[\s]*\*[\s]*DELETEALLVALUES',
])
self._testAdmxPolicy(
'RA_Unsolicit',
'Disabled',
[
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services[\s]*fAllowUnsolicited[\s]*DWORD:0',
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services[\s]*fAllowUnsolicitedFullControl[\s]*DELETE',
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services\\RAUnsolicit[\s]*\*[\s]*DELETEALLVALUES',
])
# configure RA_Unsolicit
log.debug('Attempting to configure RA_Unsolicit')
self._testAdmxPolicy('RA_Unsolicit',
{
'Configure Offer Remote Access': 'Enabled',
'Permit remote control of this computer': 'Allow helpers to remotely control the computer',
'Helpers': ['administrators', 'user1']
},
[
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services\\RAUnsolicit[\s]*user1[\s]*SZ:user1[\s]*',
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services\\RAUnsolicit[\s]*administrators[\s]*SZ:administrators[\s]*',
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services[\s]*fAllowUnsolicited[\s]*DWORD:1',
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services[\s]*fAllowUnsolicitedFullControl[\s]*DWORD:1',
])
self._testAdmxPolicy(
'RA_Unsolicit',
{
'Configure Offer Remote Access': 'Enabled',
'Permit remote control of this computer': 'Allow helpers to remotely control the computer',
'Helpers': ['administrators', 'user1']
},
[
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services\\RAUnsolicit[\s]*user1[\s]*SZ:user1[\s]*',
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services\\RAUnsolicit[\s]*administrators[\s]*SZ:administrators[\s]*',
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services[\s]*fAllowUnsolicited[\s]*DWORD:1',
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services[\s]*fAllowUnsolicitedFullControl[\s]*DWORD:1',
])
# Not Configure RA_Unsolicit
log.debug('Attempting to set RA_Unsolicit to Not Configured')
self._testAdmxPolicy('RA_Unsolicit',
'Not Configured',
[r'; Source file: c:\\windows\\system32\\grouppolicy\\machine\\registry.pol[\s]*; PARSING COMPLETED.'])
self._testAdmxPolicy(
'RA_Unsolicit',
'Not Configured',
[r'; Source file: c:\\windows\\system32\\grouppolicy\\machine\\registry.pol[\s]*; PARSING COMPLETED.'])
@destructiveTest
def test_set_computer_policy_Pol_HardenedPaths(self):
@ -344,78 +351,141 @@ class WinLgpoTest(ModuleCase):
'''
Test setting/unsetting/changing WindowsUpdate policy
'''
the_policy = {
'Configure automatic updating': '4 - Auto download and schedule the install',
'Install during automatic maintenance': False,
'Scheduled install day': '7 - Every Saturday',
'Scheduled install time': '17:00',
'Install updates for other Microsoft products': True
}
the_policy_check = [
# Configure Automatic Updates has different options in different builds
# and releases of Windows, so we'll get the elements and add them if
# they are present. Newer elements will need to be added manually as
# they are released by Microsoft
result = self.run_function(
'lgpo.get_policy_info',
['Configure Automatic Updates'],
policy_class='machine'
)
the_policy = {}
the_policy_check_enabled = [
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*NoAutoUpdate[\s]*DWORD:0',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*AUOptions[\s]*DWORD:4',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*AutomaticMaintenanceEnabled[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*ScheduledInstallDay[\s]*DWORD:7',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*ScheduledInstallTime[\s]*DWORD:17',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*AllowMUUpdateService[\s]*DWORD:1\s*'
]
# Configure Automatic Updates has different options in 2016 than in 2012
# and has only one boolean item, so we'll test it "False" in this block
# and then "True" in next block
if self.osrelease in ['2012Server', '2012ServerR2']:
the_policy = {
'Configure automatic updating': '4 - Auto download and schedule the install',
'Install during automatic maintenance': False,
'Schedule install day': '7 - Every Saturday',
'Schedule install time': '17:00',
}
the_policy_check = [
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*NoAutoUpdate[\s]*DWORD:0',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*AUOptions[\s]*DWORD:4',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*AutomaticMaintenanceEnabled[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*ScheduledInstallDay[\s]*DWORD:7',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*ScheduledInstallTime[\s]*DWORD:17',
]
# test as False
self._testAdmxPolicy(r'Windows Components\Windows Update\Configure Automatic Updates',
the_policy,
the_policy_check)
# configure as True for "enable Automatic Updates" test below
the_policy = {
'Configure automatic updating': '4 - Auto download and schedule the install',
'Install during automatic maintenance': True,
'Schedule install day': '7 - Every Saturday',
'Schedule install time': '17:00',
}
the_policy_check = [
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*NoAutoUpdate[\s]*DWORD:0',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*AUOptions[\s]*DWORD:4',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*AutomaticMaintenanceEnabled[\s]*DWORD:1\s*',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*ScheduledInstallDay[\s]*DWORD:7',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*ScheduledInstallTime[\s]*DWORD:17',
]
the_policy_check_disabled = [
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*NoAutoUpdate[\s]*DWORD:1',
]
for item in result['policy_elements']:
if 'Configure automatic updating' in item['element_aliases']:
the_policy.update({
'Configure automatic updating': '4 - Auto download and schedule the install',
})
the_policy_check_enabled.append(
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*AUOptions[\s]*DWORD:4',
)
the_policy_check_disabled.append(
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*AUOptions[\s]*DELETE',
)
elif 'Install during automatic maintenance' in item['element_aliases']:
the_policy.update({
'Install during automatic maintenance': True,
})
the_policy_check_enabled.append(
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*AutomaticMaintenanceEnabled[\s]*DWORD:1\s*',
)
the_policy_check_disabled.append(
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*AutomaticMaintenanceEnabled[\s]*DELETE',
)
elif 'Scheduled install day' in item['element_aliases']:
the_policy.update({
'Scheduled install day': '7 - Every Saturday',
})
the_policy_check_enabled.append(
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*ScheduledInstallDay[\s]*DWORD:7',
)
the_policy_check_disabled.append(
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*ScheduledInstallDay[\s]*DELETE',
)
elif 'Scheduled install time' in item['element_aliases']:
the_policy.update({
'Scheduled install time': '17:00',
})
the_policy_check_enabled.append(
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*ScheduledInstallTime[\s]*DWORD:17',
)
the_policy_check_disabled.append(
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*ScheduledInstallTime[\s]*DELETE',
)
elif 'Install updates for other Microsoft products' in item['element_aliases']:
the_policy.update({
'Install updates for other Microsoft products': True
})
the_policy_check_enabled.append(
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*AllowMUUpdateService[\s]*DWORD:1\s*'
)
the_policy_check_disabled.append(
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*AllowMUUpdateService[\s]*DELETE'
)
elif 'AutoUpdateSchEveryWeek' in item['element_aliases']:
the_policy.update({
'AutoUpdateSchEveryWeek': True
})
the_policy_check_enabled.append(
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*ScheduledInstallEveryWeek[\s]*DWORD:1\s*'
)
the_policy_check_disabled.append(
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*ScheduledInstallEveryWeek[\s]*DELETE'
)
elif 'First week of the month' in item['element_aliases']:
the_policy.update({
'First week of the month': True
})
the_policy_check_enabled.append(
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*ScheduledInstallFirstWeek[\s]*DWORD:1\s*'
)
the_policy_check_disabled.append(
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*ScheduledInstallFirstWeek[\s]*DELETE'
)
elif 'Second week of the month' in item['element_aliases']:
the_policy.update({
'Second week of the month': True
})
the_policy_check_enabled.append(
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*ScheduledInstallSecondWeek[\s]*DWORD:1\s*'
)
the_policy_check_disabled.append(
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*ScheduledInstallSecondWeek[\s]*DELETE'
)
elif 'Third week of the month' in item['element_aliases']:
the_policy.update({
'Third week of the month': True
})
the_policy_check_enabled.append(
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*ScheduledInstallThirdWeek[\s]*DWORD:1\s*'
)
the_policy_check_disabled.append(
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*ScheduledInstallThirdWeek[\s]*DELETE'
)
elif 'Fourth week of the month' in item['element_aliases']:
the_policy.update({
'Fourth week of the month': True
})
the_policy_check_enabled.append(
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*ScheduledInstallFourthWeek[\s]*DWORD:1\s*'
)
the_policy_check_disabled.append(
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*ScheduledInstallFourthWeek[\s]*DELETE'
)
# enable Automatic Updates
self._testAdmxPolicy(r'Windows Components\Windows Update\Configure Automatic Updates',
the_policy,
the_policy_check)
self._testAdmxPolicy(
r'Windows Components\Windows Update\Configure Automatic Updates',
the_policy,
the_policy_check_enabled)
# disable Configure Automatic Updates
self._testAdmxPolicy(r'Windows Components\Windows Update\Configure Automatic Updates',
'Disabled',
[
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*NoAutoUpdate[\s]*DWORD:1',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*AUOptions[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*AutomaticMaintenanceEnabled[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*ScheduledInstallDay[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*ScheduledInstallTime[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*AllowMUUpdateService[\s]*DELETE'
])
self._testAdmxPolicy(
r'Windows Components\Windows Update\Configure Automatic Updates',
'Disabled',
the_policy_check_disabled)
# set Configure Automatic Updates to 'Not Configured'
self._testAdmxPolicy(r'Windows Components\Windows Update\Configure Automatic Updates',
'Not Configured',
[r'; Source file: c:\\windows\\system32\\grouppolicy\\machine\\registry.pol[\s]*; PARSING COMPLETED.'])
self._testAdmxPolicy(
r'Windows Components\Windows Update\Configure Automatic Updates',
'Not Configured',
[r'; Source file: c:\\windows\\system32\\grouppolicy\\machine\\registry.pol[\s]*; PARSING COMPLETED.'])
@destructiveTest
def test_set_computer_policy_ClipboardRedirection(self):
@ -423,15 +493,18 @@ class WinLgpoTest(ModuleCase):
Test setting/unsetting/changing ClipboardRedirection policy
'''
# Enable/Disable/Not Configured "Do not allow Clipboard redirection"
self._testAdmxPolicy(r'Windows Components\Remote Desktop Services\Remote Desktop Session Host\Device and Resource Redirection\Do not allow Clipboard redirection',
'Enabled',
[r'Computer[\s]*Software\\Policies\\Microsoft\\Windows NT\\Terminal Services[\s]*fDisableClip[\s]*DWORD:1'])
self._testAdmxPolicy(r'Windows Components\Remote Desktop Services\Remote Desktop Session Host\Device and Resource Redirection\Do not allow Clipboard redirection',
'Disabled',
[r'Computer[\s]*Software\\Policies\\Microsoft\\Windows NT\\Terminal Services[\s]*fDisableClip[\s]*DWORD:0'])
self._testAdmxPolicy(r'Windows Components\Remote Desktop Services\Remote Desktop Session Host\Device and Resource Redirection\Do not allow Clipboard redirection',
'Not Configured',
[r'; Source file: c:\\windows\\system32\\grouppolicy\\machine\\registry.pol[\s]*; PARSING COMPLETED.'])
self._testAdmxPolicy(
r'Windows Components\Remote Desktop Services\Remote Desktop Session Host\Device and Resource Redirection\Do not allow Clipboard redirection',
'Enabled',
[r'Computer[\s]*Software\\Policies\\Microsoft\\Windows NT\\Terminal Services[\s]*fDisableClip[\s]*DWORD:1'])
self._testAdmxPolicy(
r'Windows Components\Remote Desktop Services\Remote Desktop Session Host\Device and Resource Redirection\Do not allow Clipboard redirection',
'Disabled',
[r'Computer[\s]*Software\\Policies\\Microsoft\\Windows NT\\Terminal Services[\s]*fDisableClip[\s]*DWORD:0'])
self._testAdmxPolicy(
r'Windows Components\Remote Desktop Services\Remote Desktop Session Host\Device and Resource Redirection\Do not allow Clipboard redirection',
'Not Configured',
[r'; Source file: c:\\windows\\system32\\grouppolicy\\machine\\registry.pol[\s]*; PARSING COMPLETED.'])
@destructiveTest
def test_set_computer_policy_PasswordComplexity(self):
@ -439,13 +512,15 @@ class WinLgpoTest(ModuleCase):
Test setting/unsetting/changing PasswordComplexity
'''
# disable PasswordComplexity
self._testSeceditPolicy('Password must meet complexity requirements',
'Disabled',
[r'^PasswordComplexity = 0'])
self._testSeceditPolicy(
'Password must meet complexity requirements',
'Disabled',
[r'^PasswordComplexity = 0'])
# enable PasswordComplexity
self._testSeceditPolicy('PasswordComplexity',
'Enabled',
[r'^PasswordComplexity = 1'])
self._testSeceditPolicy(
'PasswordComplexity',
'Enabled',
[r'^PasswordComplexity = 1'])
@destructiveTest
def test_set_computer_policy_PasswordLen(self):
@ -453,13 +528,15 @@ class WinLgpoTest(ModuleCase):
Test setting/unsetting/changing PasswordLength
'''
# set Minimum password length
self._testSeceditPolicy('Minimum password length',
10,
[r'^MinimumPasswordLength = 10'])
self._testSeceditPolicy(
'Minimum password length',
10,
[r'^MinimumPasswordLength = 10'])
# set MinimumPasswordLength = 0
self._testSeceditPolicy('MinPasswordLen',
0,
[r'^MinimumPasswordLength = 0'])
self._testSeceditPolicy(
'MinPasswordLen',
0,
[r'^MinimumPasswordLength = 0'])
@destructiveTest
def test_set_computer_policy_SeNetworkLogonRight(self):
@ -467,14 +544,16 @@ class WinLgpoTest(ModuleCase):
Test setting/unsetting/changing PasswordLength
'''
# set SeNetworkLogonRight to only Administrators
self._testSeceditPolicy('Access this computer from the network',
['Administrators'],
[r'^SeNetworkLogonRight = \*S-1-5-32-544'],
cumulative_rights_assignments=False)
self._testSeceditPolicy(
'Access this computer from the network',
['Administrators'],
[r'^SeNetworkLogonRight = \*S-1-5-32-544'],
cumulative_rights_assignments=False)
# set SeNetworkLogonRight back to the default
self._testSeceditPolicy('SeNetworkLogonRight',
['Everyone', 'Administrators', 'Users', 'Backup Operators'],
[r'^SeNetworkLogonRight = \*S-1-1-0,\*S-1-5-32-544,\*S-1-5-32-545,\*S-1-5-32-551'])
self._testSeceditPolicy(
'SeNetworkLogonRight',
['Everyone', 'Administrators', 'Users', 'Backup Operators'],
[r'^SeNetworkLogonRight = \*S-1-1-0,\*S-1-5-32-544,\*S-1-5-32-545,\*S-1-5-32-551'])
@destructiveTest
def test_set_computer_policy_multipleAdmxPolicies(self):
@ -482,78 +561,83 @@ class WinLgpoTest(ModuleCase):
Tests setting several ADMX policies in succession and validating the configuration w/lgop
'''
# set one policy
self._testAdmxPolicy(r'Windows Components\Remote Desktop Services\Remote Desktop Session Host\Device and Resource Redirection\Do not allow Clipboard redirection',
'Disabled',
[r'Computer[\s]*Software\\Policies\\Microsoft\\Windows NT\\Terminal Services[\s]*fDisableClip[\s]*DWORD:0'])
self._testAdmxPolicy(
r'Windows Components\Remote Desktop Services\Remote Desktop Session Host\Device and Resource Redirection\Do not allow Clipboard redirection',
'Disabled',
[r'Computer[\s]*Software\\Policies\\Microsoft\\Windows NT\\Terminal Services[\s]*fDisableClip[\s]*DWORD:0'])
# set another policy and make sure both this policy and the previous are okay
self._testAdmxPolicy('RA_Unsolicit',
{
'Configure Offer Remote Access': 'Enabled',
'Permit remote control of this computer': 'Allow helpers to remotely control the computer',
'Helpers': ['administrators', 'user1']
},
[
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows NT\\Terminal Services[\s]*fDisableClip[\s]*DWORD:0',
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services\\RAUnsolicit[\s]*user1[\s]*SZ:user1[\s]*',
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services\\RAUnsolicit[\s]*administrators[\s]*SZ:administrators[\s]*',
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services[\s]*fAllowUnsolicited[\s]*DWORD:1',
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services[\s]*fAllowUnsolicitedFullControl[\s]*DWORD:1',
])
self._testAdmxPolicy(
'RA_Unsolicit',
{
'Configure Offer Remote Access': 'Enabled',
'Permit remote control of this computer': 'Allow helpers to remotely control the computer',
'Helpers': ['administrators', 'user1']
},
[
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows NT\\Terminal Services[\s]*fDisableClip[\s]*DWORD:0',
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services\\RAUnsolicit[\s]*user1[\s]*SZ:user1[\s]*',
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services\\RAUnsolicit[\s]*administrators[\s]*SZ:administrators[\s]*',
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services[\s]*fAllowUnsolicited[\s]*DWORD:1',
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services[\s]*fAllowUnsolicitedFullControl[\s]*DWORD:1',
])
# Configure Automatic Updates and validate everything is still okay
self._testAdmxPolicy(r'Windows Components\Windows Update\Configure Automatic Updates',
'Disabled',
[
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows NT\\Terminal Services[\s]*fDisableClip[\s]*DWORD:0',
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services\\RAUnsolicit[\s]*user1[\s]*SZ:user1[\s]*',
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services\\RAUnsolicit[\s]*administrators[\s]*SZ:administrators[\s]*',
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services[\s]*fAllowUnsolicited[\s]*DWORD:1',
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services[\s]*fAllowUnsolicitedFullControl[\s]*DWORD:1',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*NoAutoUpdate[\s]*DWORD:1',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*AUOptions[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*AutomaticMaintenanceEnabled[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*ScheduledInstallDay[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*ScheduledInstallTime[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*AllowMUUpdateService[\s]*DELETE'
])
self._testAdmxPolicy(
r'Windows Components\Windows Update\Configure Automatic Updates',
'Disabled',
[
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows NT\\Terminal Services[\s]*fDisableClip[\s]*DWORD:0',
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services\\RAUnsolicit[\s]*user1[\s]*SZ:user1[\s]*',
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services\\RAUnsolicit[\s]*administrators[\s]*SZ:administrators[\s]*',
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services[\s]*fAllowUnsolicited[\s]*DWORD:1',
r'Computer[\s]*Software\\policies\\Microsoft\\Windows NT\\Terminal Services[\s]*fAllowUnsolicitedFullControl[\s]*DWORD:1',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*NoAutoUpdate[\s]*DWORD:1',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*AUOptions[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*AutomaticMaintenanceEnabled[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*ScheduledInstallDay[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*ScheduledInstallTime[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU[\s]*AllowMUUpdateService[\s]*DELETE'
])
@destructiveTest
def test_set_computer_policy_DisableDomainCreds(self):
'''
Tests Enable/Disable of DisableDomainCreds policy
'''
self._testRegistryPolicy('DisableDomainCreds',
'Enabled',
'HKEY_LOCAL_MACHINE',
'SYSTEM\\CurrentControlSet\\Control\\Lsa',
'DisableDomainCreds',
1)
self._testRegistryPolicy(
'Network access: Do not allow storage of passwords and credentials for network authentication',
'Disabled',
'HKEY_LOCAL_MACHINE',
'SYSTEM\\CurrentControlSet\\Control\\Lsa',
'DisableDomainCreds',
0)
policy_name='DisableDomainCreds',
policy_config='Enabled',
registry_value_hive='HKEY_LOCAL_MACHINE',
registry_value_path='SYSTEM\\CurrentControlSet\\Control\\Lsa',
registry_value_vname='DisableDomainCreds',
expected_value_data=1)
self._testRegistryPolicy(
policy_name='Network access: Do not allow storage of passwords and credentials for network authentication',
policy_config='Disabled',
registry_value_hive='HKEY_LOCAL_MACHINE',
registry_value_path='SYSTEM\\CurrentControlSet\\Control\\Lsa',
registry_value_vname='DisableDomainCreds',
expected_value_data=0)
@destructiveTest
def test_set_computer_policy_ForceGuest(self):
'''
Tests changing ForceGuest policy
'''
self._testRegistryPolicy('ForceGuest',
'Guest only - local users authenticate as Guest',
'HKEY_LOCAL_MACHINE',
'SYSTEM\\CurrentControlSet\\Control\\Lsa',
'ForceGuest',
1)
self._testRegistryPolicy(
'Network access: Sharing and security model for local accounts',
'Classic - local users authenticate as themselves',
'HKEY_LOCAL_MACHINE',
'SYSTEM\\CurrentControlSet\\Control\\Lsa',
'ForceGuest',
0)
policy_name='ForceGuest',
policy_config='Guest only - local users authenticate as Guest',
registry_value_hive='HKEY_LOCAL_MACHINE',
registry_value_path='SYSTEM\\CurrentControlSet\\Control\\Lsa',
registry_value_vname='ForceGuest',
expected_value_data=1)
self._testRegistryPolicy(
policy_name='Network access: Sharing and security model for local accounts',
policy_config='Classic - local users authenticate as themselves',
registry_value_hive='HKEY_LOCAL_MACHINE',
registry_value_path='SYSTEM\\CurrentControlSet\\Control\\Lsa',
registry_value_vname='ForceGuest',
expected_value_data=0)
@destructiveTest
def test_set_computer_policy_DisableUXWUAccess(self):
@ -566,34 +650,41 @@ class WinLgpoTest(ModuleCase):
if self.osrelease not in valid_osreleases:
self.skipTest('DisableUXWUAccess policy is only applicable if the osrelease grain is {0}'.format(' or '.join(valid_osreleases)))
else:
self._testAdmxPolicy(r'DisableUXWUAccess',
'Enabled',
[r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate[\s]*SetDisableUXWUAccess[\s]*DWORD:1'])
self._testAdmxPolicy(r'Remove access to use all Windows Update features',
'Disabled',
[r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate[\s]*SetDisableUXWUAccess[\s]*DWORD:0'])
self._testAdmxPolicy(r'Windows Components\Windows Update\Remove access to use all Windows Update features',
'Not Configured',
[r'; Source file: c:\\windows\\system32\\grouppolicy\\machine\\registry.pol[\s]*; PARSING COMPLETED.'])
self._testAdmxPolicy(
r'DisableUXWUAccess',
'Enabled',
[r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate[\s]*SetDisableUXWUAccess[\s]*DWORD:1'])
self._testAdmxPolicy(
r'Remove access to use all Windows Update features',
'Disabled',
[r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate[\s]*SetDisableUXWUAccess[\s]*DWORD:0'])
self._testAdmxPolicy(
r'Windows Components\Windows Update\Remove access to use all Windows Update features',
'Not Configured',
[r'; Source file: c:\\windows\\system32\\grouppolicy\\machine\\registry.pol[\s]*; PARSING COMPLETED.'])
@destructiveTest
def test_set_computer_policy_Access_data_sources_across_domains(self):
'''
Tests that a policy that has multiple names
'''
self._testAdmxPolicy(r'Access data sources across domains',
'Enabled',
[],
assert_true=False)
self._testAdmxPolicy(r'Windows Components\Internet Explorer\Internet Control Panel\Security Page\Internet Zone\Access data sources across domains',
{'Access data sources across domains': 'Prompt'},
[r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Zones\\3[\s]*1406[\s]*DWORD:1'])
self._testAdmxPolicy(r'Windows Components\Internet Explorer\Internet Control Panel\Security Page\Internet Zone\Access data sources across domains',
{'Access data sources across domains': 'Enable'},
[r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Zones\\3[\s]*1406[\s]*DWORD:0'])
self._testAdmxPolicy(r'Windows Components\Internet Explorer\Internet Control Panel\Security Page\Internet Zone\Access data sources across domains',
'Disabled',
[r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Zones\\3[\s]*1406[\s]*DELETE'])
self._testAdmxPolicy(
r'Access data sources across domains',
'Enabled',
[],
assert_true=False)
self._testAdmxPolicy(
r'Windows Components\Internet Explorer\Internet Control Panel\Security Page\Internet Zone\Access data sources across domains',
{'Access data sources across domains': 'Prompt'},
[r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Zones\\3[\s]*1406[\s]*DWORD:1'])
self._testAdmxPolicy(
r'Windows Components\Internet Explorer\Internet Control Panel\Security Page\Internet Zone\Access data sources across domains',
{'Access data sources across domains': 'Enable'},
[r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Zones\\3[\s]*1406[\s]*DWORD:0'])
self._testAdmxPolicy(
r'Windows Components\Internet Explorer\Internet Control Panel\Security Page\Internet Zone\Access data sources across domains',
'Disabled',
[r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Zones\\3[\s]*1406[\s]*DELETE'])
@destructiveTest
def test_set_computer_policy_ActiveHours(self):
@ -612,30 +703,34 @@ class WinLgpoTest(ModuleCase):
if self.osrelease not in valid_osreleases:
self.skipTest('ActiveHours policy is only applicable if the osrelease grain is {0}'.format(' or '.join(valid_osreleases)))
else:
self._testAdmxPolicy(r'ActiveHours',
{'ActiveHoursStartTime': '8 AM', 'ActiveHoursEndTime': '7 PM'},
[
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate[\s]*SetActiveHours[\s]*DWORD:1',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate[\s]*ActiveHoursStart[\s]*DWORD:8',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate[\s]*ActiveHoursEnd[\s]*DWORD:19'
])
self._testAdmxPolicy(r'ActiveHours',
{'ActiveHoursStartTime': '5 AM', 'ActiveHoursEndTime': '10 PM'},
[
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate[\s]*SetActiveHours[\s]*DWORD:1',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate[\s]*ActiveHoursStart[\s]*DWORD:5',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate[\s]*ActiveHoursEnd[\s]*DWORD:22'
])
self._testAdmxPolicy('Turn off auto-restart for updates during active hours',
'Disabled',
[
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate[\s]*SetActiveHours[\s]*DWORD:0',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate[\s]*ActiveHoursStart[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate[\s]*ActiveHoursEnd[\s]*DELETE'
])
self._testAdmxPolicy(r'Windows Components\Windows Update\Turn off auto-restart for updates during active hours',
'Not Configured',
[r'; Source file: c:\\windows\\system32\\grouppolicy\\machine\\registry.pol[\s]*; PARSING COMPLETED.'])
self._testAdmxPolicy(
r'ActiveHours',
{'ActiveHoursStartTime': '8 AM', 'ActiveHoursEndTime': '7 PM'},
[
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate[\s]*SetActiveHours[\s]*DWORD:1',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate[\s]*ActiveHoursStart[\s]*DWORD:8',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate[\s]*ActiveHoursEnd[\s]*DWORD:19'
])
self._testAdmxPolicy(
r'ActiveHours',
{'ActiveHoursStartTime': '5 AM', 'ActiveHoursEndTime': '10 PM'},
[
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate[\s]*SetActiveHours[\s]*DWORD:1',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate[\s]*ActiveHoursStart[\s]*DWORD:5',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate[\s]*ActiveHoursEnd[\s]*DWORD:22'
])
self._testAdmxPolicy(
'Turn off auto-restart for updates during active hours',
'Disabled',
[
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate[\s]*SetActiveHours[\s]*DWORD:0',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate[\s]*ActiveHoursStart[\s]*DELETE',
r'Computer[\s]*Software\\Policies\\Microsoft\\Windows\\WindowsUpdate[\s]*ActiveHoursEnd[\s]*DELETE'
])
self._testAdmxPolicy(
r'Windows Components\Windows Update\Turn off auto-restart for updates during active hours',
'Not Configured',
[r'; Source file: c:\\windows\\system32\\grouppolicy\\machine\\registry.pol[\s]*; PARSING COMPLETED.'])
@destructiveTest
def test_set_computer_policy_AllowTelemetry(self):
@ -653,21 +748,53 @@ class WinLgpoTest(ModuleCase):
{'AllowTelemetry': '1 - Basic'},
[r'Software\\Policies\\Microsoft\\Windows\\DataCollection[\s]*AllowTelemetry[\s]*DWORD:1'],
assert_true=True)
# This policy does not exist on newer Windows builds
result = self.run_function(
'state.single',
['lgpo.set'],
name='state',
computer_policy={
'Disable pre-release features or settings': 'Disabled'
}
)
name = 'lgpo_|-state_|-state_|-set'
expected = {
'new': {
'Computer Configuration': {
'Windows Components\\Data Collection and Preview Builds\\Disable pre-release features or settings': 'Disabled'}},
'old': {'Computer Configuration': {}}}
self.assertDictEqual(result[name]['changes'], expected)
'lgpo.get_policy_info',
['Disable pre-release features or settings'],
policy_class='machine')
if result['policy_found']:
result = self.run_function(
'state.single',
['lgpo.set'],
name='state',
computer_policy={
'Disable pre-release features or settings': 'Disabled'
}
)
name = 'lgpo_|-state_|-state_|-set'
expected = {
'new': {
'Computer Configuration': {
'Disable pre-release features or settings': 'Disabled'}},
'old': {
'Computer Configuration': {
'Disable pre-release features or settings': 'Not Configured'}}}
self.assertDictEqual(result[name]['changes'], expected)
else:
result = self.run_function(
'lgpo.get_policy_info',
['Manage preview builds'],
policy_class='machine'
)
if result['policy_found']:
result = self.run_function(
'state.single',
['lgpo.set'],
name='state',
computer_policy={
'Manage preview builds': 'Disabled'
}
)
name = 'lgpo_|-state_|-state_|-set'
expected = {
'new': {
'Computer Configuration': {
'Manage preview builds': 'Disabled'}},
'old': {
'Computer Configuration': {
'Manage preview builds': 'Not Configured'}}}
self.assertDictEqual(result[name]['changes'], expected)
def tearDown(self):
'''

View file

@ -523,6 +523,32 @@ class AptPkgTestCase(TestCase, LoaderModuleMockMixin):
self.assert_called_once(refresh_mock)
refresh_mock.reset_mock()
@patch('salt.utils.path.os_walk', MagicMock(return_value=[('test', 'test', 'test')]))
@patch('os.path.getsize', MagicMock(return_value=123456))
@patch('os.path.getctime', MagicMock(return_value=1234567890.123456))
@patch('fnmatch.filter', MagicMock(return_value=['/var/cache/apt/archive/test_package.rpm']))
def test_list_downloaded(self):
'''
Test downloaded packages listing.
:return:
'''
DOWNLOADED_RET = {
'test-package': {
'1.0': {
'path': '/var/cache/apt/archive/test_package.rpm',
'size': 123456,
'creation_date_time_t': 1234567890,
'creation_date_time': '2009-02-13T23:31:30',
}
}
}
with patch.dict(aptpkg.__salt__, {'lowpkg.bin_pkg_info': MagicMock(return_value={'name': 'test-package',
'version': '1.0'})}):
list_downloaded = aptpkg.list_downloaded()
self.assertEqual(len(list_downloaded), 1)
self.assertDictEqual(list_downloaded, DOWNLOADED_RET)
@skipIf(pytest is None, 'PyTest is missing')
class AptUtilsTestCase(TestCase, LoaderModuleMockMixin):

View file

@ -5,18 +5,43 @@
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
import os
# Import Salt Testing Libs
from tests.support.helpers import destructiveTest
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import TestCase, skipIf
from tests.support.mock import MagicMock, patch
# Import Salt Libs
import salt.config
import salt.modules.cmdmod
import salt.modules.file
import salt.modules.win_file as win_file
import salt.modules.win_lgpo as win_lgpo
import salt.utils.platform
import salt.utils.win_dacl
import salt.utils.win_lgpo_auditpol
import salt.utils.win_reg
LOADER_DICTS = {
win_lgpo: {
'__salt__': {
'file.file_exists': salt.modules.file.file_exists,
'file.makedirs': win_file.makedirs_,
'file.write': salt.modules.file.write,
'file.remove': win_file.remove,
'cmd.run': salt.modules.cmdmod.run},
'__opts__': salt.config.DEFAULT_MINION_OPTS.copy(),
'__utils__': {
'reg.read_value': salt.utils.win_reg.read_value,
'auditpol.get_auditpol_dump':
salt.utils.win_lgpo_auditpol.get_auditpol_dump}},
win_file: {
'__utils__': {
'dacl.set_perms': salt.utils.win_dacl.set_perms}}}
class WinSystemTestCase(TestCase):
class WinLGPOTestCase(TestCase):
'''
Test cases for salt.modules.win_lgpo
'''
@ -57,206 +82,615 @@ class WinSystemTestCase(TestCase):
value = win_lgpo._encode_string(None)
self.assertEqual(value, self.encoded_null)
def test__multi_string_get_transform_list(self):
'''
``_multi_string_get_transform`` should return the list when a list is
passed
'''
test_value = ['Spongebob', 'Squarepants']
value = win_lgpo._policy_info._multi_string_get_transform(item=test_value)
self.assertEqual(value, test_value)
@skipIf(not salt.utils.platform.is_windows(), 'Not a Windows system')
class WinLgpoNetShTestCase(TestCase, LoaderModuleMockMixin):
'''
NetSH test cases
'''
def test__multi_string_get_transform_none(self):
'''
``_multi_string_get_transform`` should return "Not Defined" when
``None`` is passed
'''
test_value = None
value = win_lgpo._policy_info._multi_string_get_transform(item=test_value)
self.assertEqual(value, 'Not Defined')
def test__multi_string_get_transform_invalid(self):
'''
``_multi_string_get_transform`` should return "Not Defined" when
``None`` is passed
'''
test_value = 'Some String'
value = win_lgpo._policy_info._multi_string_get_transform(item=test_value)
self.assertEqual(value, 'Invalid Value')
def test__multi_string_put_transform_list(self):
'''
``_multi_string_put_transform`` should return the list when a list is
passed
'''
test_value = ['Spongebob', 'Squarepants']
value = win_lgpo._policy_info._multi_string_put_transform(item=test_value)
self.assertEqual(value, test_value)
def test__multi_string_put_transform_none(self):
'''
``_multi_string_put_transform`` should return ``None`` when
"Not Defined" is passed
'''
test_value = "Not Defined"
value = win_lgpo._policy_info._multi_string_put_transform(item=test_value)
self.assertEqual(value, None)
def test__multi_string_put_transform_list_from_string(self):
'''
``_multi_string_put_transform`` should return a list when a comma
delimited string is passed
'''
test_value = "Spongebob,Squarepants"
value = win_lgpo._policy_info._multi_string_put_transform(item=test_value)
self.assertEqual(value, ['Spongebob', 'Squarepants'])
def test__multi_string_put_transform_invalid(self):
'''
``_multi_string_put_transform`` should return "Invalid" value if neither
string nor list is passed
'''
test_value = None
value = win_lgpo._policy_info._multi_string_put_transform(item=test_value)
self.assertEqual(value, "Invalid Value")
@skipIf(not salt.utils.platform.is_windows(), 'System is not Windows')
class WinLGPOGetPolicyADMXTestCase(TestCase, LoaderModuleMockMixin):
'''
Test functions related to the ``get_policy`` function using policy templates
(admx/adml)
'''
def setup_loader_modules(self):
return {win_lgpo: {
'__context__': {}
}}
return LOADER_DICTS
def test__set_netsh_value_firewall(self):
'''
Test setting the firewall inbound policy
'''
context = {
'lgpo.netsh_data': {
'Private': {
'Inbound': 'Block'}}}
def test_get_policy_name(self):
result = win_lgpo.get_policy(policy_name='Allow Telemetry',
policy_class='machine',
return_value_only=True,
return_full_policy_names=True,
hierarchical_return=False)
expected = 'Not Configured'
self.assertEqual(result, expected)
def test_get_policy_id(self):
result = win_lgpo.get_policy(policy_name='AllowTelemetry',
policy_class='machine',
return_value_only=True,
return_full_policy_names=True,
hierarchical_return=False)
expected = 'Not Configured'
self.assertEqual(result, expected)
def test_get_policy_name_full_return_full_names(self):
result = win_lgpo.get_policy(policy_name='Allow Telemetry',
policy_class='machine',
return_value_only=False,
return_full_policy_names=True,
hierarchical_return=False)
expected = {
'lgpo.netsh_data': {
'Private': {
'Inbound': 'Allow'}}}
with patch('salt.utils.win_lgpo_netsh.set_firewall_settings',
MagicMock(return_value=True)),\
patch.dict(win_lgpo.__context__, context):
result = win_lgpo._set_netsh_value(profile='Private',
section='firewallpolicy',
option='Inbound',
value='Allow')
self.assertTrue(result)
self.assertEqual(win_lgpo.__context__, expected)
'Windows Components\\Data Collection and Preview Builds\\'
'Allow Telemetry': 'Not Configured'}
self.assertDictEqual(result, expected)
def test__set_netsh_value_settings(self):
'''
Test setting firewall settings
'''
context = {
'lgpo.netsh_data': {
'private': {
'localfirewallrules': 'disable'}}}
def test_get_policy_id_full_return_full_names(self):
result = win_lgpo.get_policy(policy_name='AllowTelemetry',
policy_class='machine',
return_value_only=False,
return_full_policy_names=True,
hierarchical_return=False)
expected = {
'lgpo.netsh_data': {
'private': {
'localfirewallrules': 'enable'}}}
with patch('salt.utils.win_lgpo_netsh.set_settings',
MagicMock(return_value=True)), \
patch.dict(win_lgpo.__context__, context):
result = win_lgpo._set_netsh_value(profile='private',
section='settings',
option='localfirewallrules',
value='enable')
self.assertTrue(result)
self.assertEqual(win_lgpo.__context__, expected)
'Windows Components\\Data Collection and Preview Builds\\'
'Allow Telemetry': 'Not Configured'}
self.assertDictEqual(result, expected)
def test__set_netsh_value_state(self):
'''
Test setting the firewall state
'''
context = {
'lgpo.netsh_data': {
'private': {
'State': 'notconfigured'}}}
def test_get_policy_name_full_return_ids(self):
result = win_lgpo.get_policy(policy_name='Allow Telemetry',
policy_class='machine',
return_value_only=False,
return_full_policy_names=False,
hierarchical_return=False)
expected = {'AllowTelemetry': 'Not Configured'}
self.assertDictEqual(result, expected)
def test_get_policy_id_full_return_ids(self):
result = win_lgpo.get_policy(policy_name='AllowTelemetry',
policy_class='machine',
return_value_only=False,
return_full_policy_names=False,
hierarchical_return=False)
expected = {'AllowTelemetry': 'Not Configured'}
self.assertDictEqual(result, expected)
def test_get_policy_id_full_return_ids_hierarchical(self):
result = win_lgpo.get_policy(policy_name='AllowTelemetry',
policy_class='machine',
return_value_only=False,
return_full_policy_names=False,
hierarchical_return=True)
expected = {
'lgpo.netsh_data': {
'private': {
'State': 'on'}}}
with patch('salt.utils.win_lgpo_netsh.set_state',
MagicMock(return_value=True)), \
patch.dict(win_lgpo.__context__, context):
result = win_lgpo._set_netsh_value(profile='private',
section='state',
option='unused',
value='on')
self.assertTrue(result)
self.assertEqual(win_lgpo.__context__, expected)
'Computer Configuration': {
'Administrative Templates': {
'WindowsComponents': {
'DataCollectionAndPreviewBuilds': {
'AllowTelemetry': 'Not Configured'}}}}}
self.assertDictEqual(result, expected)
def test__set_netsh_value_logging(self):
'''
Test setting firewall logging
'''
context = {
'lgpo.netsh_data': {
'private': {
'allowedconnections': 'notconfigured'}}}
def test_get_policy_name_return_full_names_hierarchical(self):
result = win_lgpo.get_policy(policy_name='Allow Telemetry',
policy_class='machine',
return_value_only=False,
return_full_policy_names=True,
hierarchical_return=True)
expected = {
'lgpo.netsh_data': {
'private': {
'allowedconnections': 'enable'}}}
with patch('salt.utils.win_lgpo_netsh.set_logging_settings',
MagicMock(return_value=True)), \
patch.dict(win_lgpo.__context__, context):
result = win_lgpo._set_netsh_value(profile='private',
section='logging',
option='allowedconnections',
value='enable')
self.assertTrue(result)
self.assertEqual(win_lgpo.__context__, expected)
'Computer Configuration': {
'Administrative Templates': {
'Windows Components': {
'Data Collection and Preview Builds': {
'Allow Telemetry': 'Not Configured'}}}}}
self.assertDictEqual(result, expected)
class WinLgpoSeceditTestCase(TestCase, LoaderModuleMockMixin):
@skipIf(not salt.utils.platform.is_windows(), 'System is not Windows')
class WinLGPOGetPolicyFromPolicyInfoTestCase(TestCase, LoaderModuleMockMixin):
'''
Secedit test cases
Test functions related to the ``get_policy`` function using _policy_info
object
'''
def setup_loader_modules(self):
return LOADER_DICTS
def test_get_policy_name(self):
result = win_lgpo.get_policy(
policy_name='Network firewall: Public: Settings: Display a '
'notification',
policy_class='machine',
return_value_only=True,
return_full_policy_names=True,
hierarchical_return=False)
expected = 'Not configured'
self.assertEqual(result, expected)
def test_get_policy_id(self):
result = win_lgpo.get_policy(
policy_name='WfwPublicSettingsNotification',
policy_class='machine',
return_value_only=True,
return_full_policy_names=True,
hierarchical_return=False)
expected = 'Not configured'
self.assertEqual(result, expected)
def test_get_policy_name_full_return(self):
result = win_lgpo.get_policy(
policy_name='Network firewall: Public: Settings: Display a '
'notification',
policy_class='machine',
return_value_only=False,
return_full_policy_names=True,
hierarchical_return=False)
expected = {
'Network firewall: Public: Settings: Display a notification':
'Not configured'}
self.assertDictEqual(result, expected)
def test_get_policy_id_full_return(self):
result = win_lgpo.get_policy(
policy_name='WfwPublicSettingsNotification',
policy_class='machine',
return_value_only=False,
return_full_policy_names=True,
hierarchical_return=False)
expected = {
'Network firewall: Public: Settings: Display a notification':
'Not configured'}
self.assertDictEqual(result, expected)
def test_get_policy_name_full_return_ids(self):
result = win_lgpo.get_policy(
policy_name='Network firewall: Public: Settings: Display a '
'notification',
policy_class='machine',
return_value_only=False,
return_full_policy_names=False,
hierarchical_return=False)
expected = {
'Network firewall: Public: Settings: Display a notification':
'Not configured'}
self.assertDictEqual(result, expected)
def test_get_policy_id_full_return_ids(self):
result = win_lgpo.get_policy(
policy_name='WfwPublicSettingsNotification',
policy_class='machine',
return_value_only=False,
return_full_policy_names=False,
hierarchical_return=False)
expected = {'WfwPublicSettingsNotification': 'Not configured'}
self.assertDictEqual(result, expected)
def test_get_policy_id_full_return_ids_hierarchical(self):
result = win_lgpo.get_policy(
policy_name='WfwPublicSettingsNotification',
policy_class='machine',
return_value_only=False,
return_full_policy_names=False,
hierarchical_return=True)
expected = {
'Computer Configuration': {
'Windows Settings': {
'Security Settings': {
'Windows Firewall with Advanced Security': {
'Windows Firewall with Advanced Security - Local '
'Group Policy Object': {
'WfwPublicSettingsNotification':
'Not configured'}}}}}}
self.assertDictEqual(result, expected)
def test_get_policy_id_full_return_full_names_hierarchical(self):
result = win_lgpo.get_policy(
policy_name='WfwPublicSettingsNotification',
policy_class='machine',
return_value_only=False,
return_full_policy_names=True,
hierarchical_return=True)
expected = {
'Computer Configuration': {
'Windows Settings': {
'Security Settings': {
'Windows Firewall with Advanced Security': {
'Windows Firewall with Advanced Security - Local '
'Group Policy Object': {
'Network firewall: Public: Settings: Display a '
'notification':
'Not configured'}}}}}}
self.assertDictEqual(result, expected)
@skipIf(not salt.utils.platform.is_windows(), 'System is not Windows')
class WinLGPOPolicyInfoMechanismsTestCase(TestCase, LoaderModuleMockMixin):
'''
Test getting local group policy settings defined in the _policy_info object
Go through each mechanism
'''
def setup_loader_modules(self):
return LOADER_DICTS
@classmethod
def setUpClass(cls):
cls.secedit_data = [
'[Unicode]',
'Unicode=yes',
'[System Access]',
'MinimumPasswordAge = 0',
'MaximumPasswordAge = 42',
'[Event Audit]',
'AuditSystemEvents = 0',
'AuditLogonEvents = 0',
'[Registry Values]',
r'MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Setup\RecoveryConsole\SecurityLevel=4,0',
r'MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Setup\RecoveryConsole\SetCommand=4,0',
'[Privilege Rights]',
'SeNetworkLogonRight = *S-1-1-0,*S-1-5-32-544,*S-1-5-32-545,*S-1-5-32-551',
'SeBackupPrivilege = *S-1-5-32-544,*S-1-5-32-551',
'[Version]',
'signature="$CHICAGO$"',
'Revision=1']
cls.policy_data = salt.modules.win_lgpo._policy_info()
@classmethod
def tearDownClass(cls):
del cls.secedit_data
def _test_policy(self, policy_name):
'''
Helper function to get current setting
'''
policy_definition = self.policy_data.policies['Machine']['policies'][policy_name]
return salt.modules.win_lgpo._get_policy_info_setting(policy_definition)
def test_registry_mechanism(self):
'''
Test getting policy value using the Registry mechanism
'''
policy_name = 'RemoteRegistryExactPaths'
result = self._test_policy(policy_name=policy_name)
expected = [
'System\\CurrentControlSet\\Control\\ProductOptions',
'System\\CurrentControlSet\\Control\\Server Applications',
'Software\\Microsoft\\Windows NT\\CurrentVersion'
]
self.assertListEqual(result, expected)
def test_secedit_mechanism(self):
'''
Test getting policy value using the Secedit mechanism
'''
policy_name = 'LSAAnonymousNameLookup'
result = self._test_policy(policy_name=policy_name)
expected = 'Disabled'
self.assertEqual(result, expected)
def test_netsh_mechanism(self):
'''
Test getting the policy value using the NetSH mechanism
'''
policy_name = 'WfwDomainState'
result = self._test_policy(policy_name=policy_name)
expected = 'Not configured'
self.assertEqual(result, expected)
@destructiveTest
def test_adv_audit_mechanism(self):
'''
Test getting the policy value using the AdvAudit mechanism
'''
system_root = os.environ.get('SystemRoot', 'C:\\Windows')
f_audit = os.path.join(system_root, 'security', 'audit', 'audit.csv')
f_audit_gpo = os.path.join(system_root, 'System32', 'GroupPolicy',
'Machine', 'Microsoft', 'Windows NT',
'Audit', 'audit.csv')
if os.path.exists(f_audit):
os.remove(f_audit)
if os.path.exists(f_audit_gpo):
os.remove(f_audit_gpo)
policy_name = 'AuditCredentialValidation'
result = self._test_policy(policy_name=policy_name)
expected = 'Not Configured'
self.assertEqual(result, expected)
def test_net_user_modal_mechanism(self):
'''
Test getting the policy value using the NetUserModal mechanism
'''
policy_name = 'PasswordHistory'
result = self._test_policy(policy_name=policy_name)
expected = 0
self.assertEqual(result, expected)
def test_lsa_rights_mechanism(self):
'''
Test getting the policy value using the LsaRights mechanism
'''
policy_name = 'SeTrustedCredManAccessPrivilege'
result = self._test_policy(policy_name=policy_name)
expected = []
self.assertEqual(result, expected)
def test_script_ini_mechanism(self):
'''
Test getting the policy value using the ScriptIni value
'''
policy_name = 'StartupScripts'
result = self._test_policy(policy_name=policy_name)
expected = None
self.assertEqual(result, expected)
@destructiveTest
@skipIf(not salt.utils.platform.is_windows(), 'System is not Windows')
class WinLGPOGetPointAndPrintNCTestCase(TestCase, LoaderModuleMockMixin):
'''
Test variations of the Point and Print Restrictions policy when Not
Configured (NC)
'''
not_configured = False
def setup_loader_modules(self):
return {win_lgpo: {
'__context__': {},
'__opts__': {'cachedir': 'C:\\cachedir'},
'__salt__': {}
}}
return LOADER_DICTS
def test__get_secedit_data(self):
def setUp(self):
if not self.not_configured:
computer_policy = {'Point and Print Restrictions': 'Not Configured'}
win_lgpo.set_(computer_policy=computer_policy)
self.not_configured = True
def _get_policy_adm_setting(self, policy_name, policy_class,
return_full_policy_names, hierarchical_return):
'''
Test getting secedit data and loading it into __context__
Helper function to get current setting
'''
# Get the policy
success, policy_obj, _, _ = salt.modules.win_lgpo._lookup_admin_template(
policy_name=policy_name,
policy_class=policy_class,
adml_language='en-US')
if success:
return salt.modules.win_lgpo._get_policy_adm_setting(
admx_policy=policy_obj,
policy_class=policy_class,
adml_language='en-US',
return_full_policy_names=return_full_policy_names,
hierarchical_return=hierarchical_return
)
return 'Policy Not Found'
def test_point_and_print_not_configured(self):
result = self._get_policy_adm_setting(
policy_name='Point and Print Restrictions',
policy_class='Machine',
return_full_policy_names=False,
hierarchical_return=False
)
expected = {
'AuditLogonEvents': '0',
'AuditSystemEvents': '0',
r'MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Setup\RecoveryConsole\SecurityLevel': '4,0',
r'MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Setup\RecoveryConsole\SetCommand': '4,0',
'MaximumPasswordAge': '42',
'MinimumPasswordAge': '0',
'Revision': '1',
'SeBackupPrivilege': '*S-1-5-32-544,*S-1-5-32-551',
'SeNetworkLogonRight': '*S-1-1-0,*S-1-5-32-544,*S-1-5-32-545,*S-1-5-32-551',
'Unicode': 'yes',
'signature': '"$CHICAGO$"'}
with patch.object(win_lgpo, '_load_secedit_data',
MagicMock(return_value=self.secedit_data)):
result = win_lgpo._get_secedit_data()
self.assertDictEqual(result, expected)
self.assertDictEqual(win_lgpo.__context__['lgpo.secedit_data'],
expected)
'PointAndPrint_Restrictions_Win7': 'Not Configured'
}
self.assertDictEqual(result, expected)
def test__get_secedit_value(self):
'''
Test getting a specific secedit value
'''
with patch.object(win_lgpo, '_load_secedit_data',
MagicMock(return_value=self.secedit_data)):
result = win_lgpo._get_secedit_value('AuditSystemEvents')
self.assertEqual(result, '0')
def test_point_and_print_not_configured_hierarchical(self):
result = self._get_policy_adm_setting(
policy_name='Point and Print Restrictions',
policy_class='Machine',
return_full_policy_names=False,
hierarchical_return=True
)
expected = {
'Computer Configuration': {
'Administrative Templates': {
'Printers': {
'PointAndPrint_Restrictions_Win7':
'Not Configured'}}}}
self.assertDictEqual(result, expected)
def test__get_secedit_value_not_defined(self):
'''
Test getting a secedit value that is undefined
'''
with patch.object(win_lgpo, '_load_secedit_data',
MagicMock(return_value=self.secedit_data)):
result = win_lgpo._get_secedit_value('UndefinedKey')
self.assertEqual(result, 'Not Defined')
def test_point_and_print_not_configured_full_names(self):
result = self._get_policy_adm_setting(
policy_name='Point and Print Restrictions',
policy_class='Machine',
return_full_policy_names=True,
hierarchical_return=False
)
expected = {
'Printers\\Point and Print Restrictions': 'Not Configured'
}
self.assertDictEqual(result, expected)
def test__write_secedit_data(self):
def test_point_and_print_not_configured_full_names_hierarchical(self):
result = self._get_policy_adm_setting(
policy_name='Point and Print Restrictions',
policy_class='Machine',
return_full_policy_names=True,
hierarchical_return=True
)
expected = {
'Computer Configuration': {
'Administrative Templates': {
'Printers': {
'Point and Print Restrictions':
'Not Configured'}}}}
self.assertDictEqual(result, expected)
@destructiveTest
@skipIf(not salt.utils.platform.is_windows(), 'System is not Windows')
class WinLGPOGetPointAndPrintENTestCase(TestCase, LoaderModuleMockMixin):
'''
Test variations of the Point and Print Restrictions policy when Enabled (EN)
'''
configured = False
def setup_loader_modules(self):
return LOADER_DICTS
def setUp(self):
if not self.configured:
computer_policy = {
'Point and Print Restrictions': {
'Users can only point and print to these servers':
True,
'Enter fully qualified server names separated by '
'semicolons':
'fakeserver1;fakeserver2',
'Users can only point and print to machines in their '
'forest':
True,
'Security Prompts: When installing drivers for a new '
'connection':
'Show warning and elevation prompt',
'When updating drivers for an existing connection':
'Show warning only',
},
}
win_lgpo.set_(computer_policy=computer_policy)
self.configured = True
def _get_policy_adm_setting(self, policy_name, policy_class,
return_full_policy_names, hierarchical_return):
'''
Test writing secedit data and updating the __context__
Helper function to get current setting
'''
mock_true = MagicMock(return_value=True)
mock_false = MagicMock(return_value=False)
mock_retcode = MagicMock(return_value=0)
new_secedit_data = {'System Access': ['MaximumPasswordAge=100']}
with patch.object(win_lgpo, '_load_secedit_data',
MagicMock(return_value=self.secedit_data)),\
patch.dict(win_lgpo.__salt__, {'file.write': mock_true,
'file.file_exists': mock_false,
'cmd.retcode': mock_retcode}):
# Populate __context__['lgpo.secedit_data']
# It will have been run before this function is called
win_lgpo._get_secedit_data()
self.assertEqual(
win_lgpo.__context__['lgpo.secedit_data']['MaximumPasswordAge'],
'42')
result = win_lgpo._write_secedit_data(new_secedit_data)
self.assertTrue(result)
self.assertEqual(
win_lgpo.__context__['lgpo.secedit_data']['MaximumPasswordAge'],
'100')
# Get the policy
success, policy_obj, _, _ = salt.modules.win_lgpo._lookup_admin_template(
policy_name=policy_name,
policy_class=policy_class,
adml_language='en-US')
if success:
return salt.modules.win_lgpo._get_policy_adm_setting(
admx_policy=policy_obj,
policy_class=policy_class,
adml_language='en-US',
return_full_policy_names=return_full_policy_names,
hierarchical_return=hierarchical_return
)
return 'Policy Not Found'
def test_point_and_print_enabled(self):
result = self._get_policy_adm_setting(
policy_name='Point and Print Restrictions',
policy_class='Machine',
return_full_policy_names=False,
hierarchical_return=False
)
expected = {
'PointAndPrint_Restrictions_Win7': {
'PointAndPrint_NoWarningNoElevationOnInstall_Enum':
'Show warning and elevation prompt',
'PointAndPrint_NoWarningNoElevationOnUpdate_Enum':
'Show warning only',
'PointAndPrint_TrustedForest_Chk':
True,
'PointAndPrint_TrustedServers_Chk':
True,
u'PointAndPrint_TrustedServers_Edit':
'fakeserver1;fakeserver2'}}
self.assertDictEqual(result, expected)
def test_point_and_print_enabled_hierarchical(self):
result = self._get_policy_adm_setting(
policy_name='Point and Print Restrictions',
policy_class='Machine',
return_full_policy_names=False,
hierarchical_return=True
)
expected = {
'Computer Configuration': {
'Administrative Templates': {
'Printers': {
'PointAndPrint_Restrictions_Win7': {
'PointAndPrint_NoWarningNoElevationOnInstall_Enum':
'Show warning and elevation prompt',
'PointAndPrint_NoWarningNoElevationOnUpdate_Enum':
'Show warning only',
'PointAndPrint_TrustedForest_Chk':
True,
'PointAndPrint_TrustedServers_Chk':
True,
u'PointAndPrint_TrustedServers_Edit':
'fakeserver1;fakeserver2'}}}}}
self.assertDictEqual(result, expected)
def test_point_and_print_enabled_full_names(self):
result = self._get_policy_adm_setting(
policy_name='Point and Print Restrictions',
policy_class='Machine',
return_full_policy_names=True,
hierarchical_return=False
)
expected = {
'Printers\\Point and Print Restrictions': {
'Enter fully qualified server names separated by semicolons':
'fakeserver1;fakeserver2',
'Security Prompts: When installing drivers for a new '
'connection':
'Show warning and elevation prompt',
'Users can only point and print to machines in their forest':
True,
u'Users can only point and print to these servers': True,
u'When updating drivers for an existing connection':
'Show warning only'}}
self.assertDictEqual(result, expected)
def test_point_and_print_enabled_full_names_hierarchical(self):
result = self._get_policy_adm_setting(
policy_name='Point and Print Restrictions',
policy_class='Machine',
return_full_policy_names=True,
hierarchical_return=True
)
expected = {
'Computer Configuration': {
'Administrative Templates': {
'Printers': {
'Point and Print Restrictions': {
'Enter fully qualified server names separated by '
'semicolons':
'fakeserver1;fakeserver2',
'Security Prompts: When installing drivers for a '
'new connection':
'Show warning and elevation prompt',
'Users can only point and print to machines in '
'their forest':
True,
u'Users can only point and print to these servers':
True,
u'When updating drivers for an existing connection':
'Show warning only'}}}}}
self.assertDictEqual(result, expected)

View file

@ -98,3 +98,30 @@ class WinSystemTestCase(TestCase):
self.assertFalse(
win_lgpo._compare_policies(compare_dict, None)
)
def test__compare_policies_integer(self):
'''
``_compare_policies`` should only return ``True`` when the integer
values are the same. All other scenarios should return ``False``
'''
compare_integer = 1
# Same
self.assertTrue(
win_lgpo._compare_policies(compare_integer, compare_integer)
)
# Different
self.assertFalse(
win_lgpo._compare_policies(compare_integer, 0)
)
# List
self.assertFalse(
win_lgpo._compare_policies(compare_integer, ['item1', 'item2'])
)
# Dict
self.assertFalse(
win_lgpo._compare_policies(compare_integer, {'key': 'value'})
)
# None
self.assertFalse(
win_lgpo._compare_policies(compare_integer, None)
)

View file

@ -2,6 +2,7 @@
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext import six
# Import Salt Testing Libs
from tests.support.helpers import destructiveTest, generate_random_name
@ -176,6 +177,40 @@ class WinFunctionsTestCase(TestCase):
expected
)
@destructiveTest
def test_read_value_multi_sz_empty_list(self):
'''
An empty REG_MULTI_SZ value should return an empty list, not None
'''
try:
self.assertTrue(
win_reg.set_value(
hive='HKLM',
key=FAKE_KEY,
vname='empty_list',
vdata=[],
vtype='REG_MULTI_SZ'
)
)
expected = {
'hive': 'HKLM',
'key': FAKE_KEY,
'success': True,
'vdata': [],
'vname': 'empty_list',
'vtype': 'REG_MULTI_SZ'
}
self.assertEqual(
win_reg.read_value(
hive='HKLM',
key=FAKE_KEY,
vname='empty_list',
),
expected
)
finally:
win_reg.delete_key_recursive(hive='HKLM', key=FAKE_KEY)
@destructiveTest
def test_set_value(self):
'''
@ -462,3 +497,13 @@ class WinFunctionsTestCase(TestCase):
)
finally:
win_reg.delete_key_recursive(hive='HKLM', key=FAKE_KEY)
def test__to_unicode_int(self):
'''
Test the ``_to_unicode`` function when it receives an integer value.
Should return a unicode value, which is unicode in PY2 and str in PY3.
'''
if six.PY3:
self.assertTrue(isinstance(win_reg._to_unicode(1), str))
else:
self.assertTrue(isinstance(win_reg._to_unicode(1), unicode)) # pylint: disable=incompatible-py3-code,undefined-variable