Fix lgpo issue on Py3

Open the gpt ini file in normal mode (not binary)
Use log.exception so you can see where the actual problems are
Add TODOs to make the exceptions more specific
This commit is contained in:
twangboy 2018-07-13 15:43:57 -06:00
parent 5b5a930449
commit bfcbdeca3b
No known key found for this signature in database
GPG key ID: 93FF3BDEB278C9EB

View file

@ -2588,7 +2588,9 @@ class _policy_info(object):
userSid = '{1}\\{0}'.format(userSid[0], userSid[1])
else:
userSid = '{0}'.format(userSid[0])
# TODO: This needs to be more specific
except Exception:
log.exception('Handle this explicitly')
userSid = win32security.ConvertSidToStringSid(_sid)
usernames.append(userSid)
return usernames
@ -2607,7 +2609,9 @@ class _policy_info(object):
try:
sid = win32security.LookupAccountName('', _user)[0]
sids.append(sid)
# This needs to be more specific
except Exception as e:
log.exception('Handle this explicitly')
raise CommandExecutionError((
'There was an error obtaining the SID of user "{0}". Error '
'returned: {1}'
@ -2760,7 +2764,9 @@ def _processPolicyDefinitions(policy_def_path='c:\\Windows\\PolicyDefinitions',
except lxml.etree.XMLSyntaxError:
try:
xmltree = _remove_unicode_encoding(admfile)
# TODO: This needs to be more specific
except Exception:
log.exception('Handle this explicitly')
log.error('A error was found while processing admx '
'file %s, all policies from this file will '
'be unavailable via this module', admfile)
@ -2845,7 +2851,9 @@ def _processPolicyDefinitions(policy_def_path='c:\\Windows\\PolicyDefinitions',
# see issue #38100
try:
xmltree = _remove_unicode_encoding(adml_file)
# TODO: This needs to be more specific
except Exception:
log.exception('Handle this explicitly')
log.error('An error was found while processing '
'adml file %s, all policy '
'language data from this file will be '
@ -2901,8 +2909,9 @@ def _findOptionValueInSeceditFile(option):
if _line.startswith(option):
return True, _line.split('=')[1].strip()
return True, 'Not Defined'
except Exception as e:
log.debug('error occurred while trying to get secedit data')
# TODO: This needs to be more specific
except Exception:
log.exception('error occurred while trying to get secedit data')
return False, None
@ -2932,8 +2941,9 @@ def _importSeceditConfig(infdata):
if __salt__['file.file_exists'](_tInfFile):
_ret = __salt__['file.remove'](_tInfFile)
return True
# TODO: This needs to be more specific
except Exception as e:
log.debug('error occurred while trying to import secedit data')
log.exception('error occurred while trying to import secedit data')
return False
@ -2995,9 +3005,10 @@ def _addAccountRights(sidObject, user_right):
user_rights_list = [user_right]
_ret = win32security.LsaAddAccountRights(_polHandle, sidObject, user_rights_list)
return True
# TODO: This needs to be more specific
except Exception as e:
log.error('Error attempting to add account right, exception was %s',
e)
log.exception('Error attempting to add account right, exception was %s',
e)
return False
@ -3011,8 +3022,7 @@ def _delAccountRights(sidObject, user_right):
_ret = win32security.LsaRemoveAccountRights(_polHandle, sidObject, False, user_rights_list)
return True
except Exception as e:
log.error('Error attempting to delete account right, '
'exception was %s', e)
log.exception('Error attempting to delete account right')
return False
@ -4180,7 +4190,7 @@ def _write_regpol_data(data_to_write,
try:
reg_pol_header = u'\u5250\u6765\x01\x00'
if not os.path.exists(policy_file_path):
ret = __salt__['file.makedirs'](policy_file_path)
__salt__['file.makedirs'](policy_file_path)
with salt.utils.files.fopen(policy_file_path, 'wb') as pol_file:
if not data_to_write.startswith(reg_pol_header.encode('utf-16-le')):
pol_file.write(reg_pol_header.encode('utf-16-le'))
@ -4188,11 +4198,12 @@ def _write_regpol_data(data_to_write,
try:
gpt_ini_data = ''
if os.path.exists(gpt_ini_path):
with salt.utils.files.fopen(gpt_ini_path, 'rb') as gpt_file:
with salt.utils.files.fopen(gpt_ini_path, 'r') as gpt_file:
gpt_ini_data = gpt_file.read()
if not _regexSearchRegPolData(r'\[General\]\r\n', gpt_ini_data):
gpt_ini_data = '[General]\r\n' + gpt_ini_data
if _regexSearchRegPolData(r'{0}='.format(re.escape(gpt_extension)), gpt_ini_data):
if _regexSearchRegPolData(r'{0}='.format(re.escape(gpt_extension)),
gpt_ini_data):
# ensure the line contains the ADM guid
gpt_ext_loc = re.search(r'^{0}=.*\r\n'.format(re.escape(gpt_extension)),
gpt_ini_data,
@ -4208,9 +4219,10 @@ def _write_regpol_data(data_to_write,
general_location = re.search(r'^\[General\]\r\n',
gpt_ini_data,
re.IGNORECASE | re.MULTILINE)
gpt_ini_data = "{0}{1}={2}\r\n{3}".format(
gpt_ini_data = '{0}{1}={2}\r\n{3}'.format(
gpt_ini_data[general_location.start():general_location.end()],
gpt_extension, gpt_extension_guid,
gpt_extension,
gpt_extension_guid,
gpt_ini_data[general_location.end():])
# https://technet.microsoft.com/en-us/library/cc978247.aspx
if _regexSearchRegPolData(r'Version=', gpt_ini_data):
@ -4225,9 +4237,10 @@ def _write_regpol_data(data_to_write,
elif gpt_extension.lower() == 'gPCUserExtensionNames'.lower():
version_nums = (version_nums[0] + 1, version_nums[1])
version_num = struct.unpack(b'>I', struct.pack(b'>2H', *version_nums))[0]
gpt_ini_data = "{0}{1}={2}\r\n{3}".format(
gpt_ini_data = '{0}{1}={2}\r\n{3}'.format(
gpt_ini_data[0:version_loc.start()],
'Version', version_num,
'Version',
version_num,
gpt_ini_data[version_loc.end():])
else:
general_location = re.search(r'^\[General\]\r\n',
@ -4237,20 +4250,26 @@ def _write_regpol_data(data_to_write,
version_nums = (0, 1)
elif gpt_extension.lower() == 'gPCUserExtensionNames'.lower():
version_nums = (1, 0)
gpt_ini_data = "{0}{1}={2}\r\n{3}".format(
gpt_ini_data = '{0}{1}={2}\r\n{3}'.format(
gpt_ini_data[general_location.start():general_location.end()],
'Version',
int("{0}{1}".format(six.text_type(version_nums[0]).zfill(4), six.text_type(version_nums[1]).zfill(4)), 16),
int("{0}{1}".format(six.text_type(version_nums[0]).zfill(4),
six.text_type(version_nums[1]).zfill(4)),
16),
gpt_ini_data[general_location.end():])
if gpt_ini_data:
with salt.utils.files.fopen(gpt_ini_path, 'wb') as gpt_file:
gpt_file.write(salt.utils.stringutils.to_bytes(gpt_ini_data))
# TODO: This needs to be more specific
except Exception as e:
msg = 'An error occurred attempting to write to {0}, the exception was {1}'.format(
gpt_ini_path, e)
log.exception(msg)
raise CommandExecutionError(msg)
# TODO: This needs to be more specific
except Exception as e:
msg = 'An error occurred attempting to write to {0}, the exception was {1}'.format(policy_file_path, e)
log.exception(msg)
raise CommandExecutionError(msg)
@ -4648,8 +4667,9 @@ def _writeAdminTemplateRegPolFile(admtemplate_data,
policy_data.gpt_ini_path,
policy_data.admx_registry_classes[registry_class]['gpt_extension_location'],
policy_data.admx_registry_classes[registry_class]['gpt_extension_guid'])
# TODO: This needs to be more specific or removed
except Exception:
log.error('Unhandled exception %s occurred while attempting to write Adm Template Policy File')
log.exception('Unhandled exception %s occurred while attempting to write Adm Template Policy File')
return False
return True
@ -4671,7 +4691,7 @@ def _getScriptSettingsFromIniFile(policy_info):
_existingData = deserialize(_existingData.decode('utf-16-le').lstrip('\ufeff'))
log.debug('Have deserialized data %s', _existingData)
except Exception as error:
log.error('An error occurred attempting to deserialize data for %s', policy_info['Policy'])
log.exception('An error occurred attempting to deserialize data for %s', policy_info['Policy'])
raise CommandExecutionError(error)
if 'Section' in policy_info['ScriptIni'] and policy_info['ScriptIni']['Section'].lower() in [z.lower() for z in _existingData.keys()]:
if 'SettingName' in policy_info['ScriptIni']:
@ -5540,8 +5560,10 @@ def set_(computer_policy=None, user_policy=None,
_newModalSetData = dictupdate.update(_existingModalData, _modal_sets[_modal_set])
log.debug('NEW MODAL SET = %s', _newModalSetData)
_ret = win32net.NetUserModalsSet(None, _modal_set, _newModalSetData)
except:
# TODO: This needs to be more specific
except Exception:
msg = 'An unhandled exception occurred while attempting to set policy via NetUserModalSet'
log.exception(msg)
raise CommandExecutionError(msg)
if _admTemplateData:
_ret = False