2
0
mirror of https://gitlab.com/apparmor/apparmor synced 2025-08-31 06:16:03 +00:00

Remove redundant backslashes, and unnecessary semicolons and pass statements.

This commit is contained in:
Mark Grassi
2022-08-07 13:40:59 -04:00
parent 813c831468
commit f590a66e50
11 changed files with 56 additions and 65 deletions

View File

@@ -331,7 +331,7 @@ class AAParserCachingTests(AAParserCachingCommon):
features_file = testlib.write_file(self.cache_dir, '.features', 'monkey\n')
new_file = self.get_cache_dir()
new_features_file = new_file + '/.features';
new_features_file = new_file + '/.features'
cmd = list(self.cmd_prefix)
cmd.extend(('-v', '--write-cache', '-r', self.profile))

View File

@@ -121,7 +121,6 @@ class AATestTemplate(unittest.TestCase, metaclass=AANoCleanupMetaClass):
# Timeout handler using alarm() from John P. Speno's Pythonic Avocado
class TimeoutFunctionException(Exception):
"""Exception to raise on a timeout"""
pass
class TimeoutFunction:

View File

@@ -282,30 +282,28 @@ class AppArmorEasyProfile:
if opt.templates_dir and os.path.isdir(opt.templates_dir):
self.dirs['templates'] = os.path.abspath(opt.templates_dir)
elif not opt.templates_dir and \
opt.template and \
os.path.isfile(opt.template) and \
valid_path(opt.template):
elif (not opt.templates_dir
and opt.template
and os.path.isfile(opt.template)
and valid_path(opt.template)):
# If we specified the template and it is an absolute path, just set
# the templates directory to the parent of the template so we don't
# have to require --template-dir with absolute paths.
self.dirs['templates'] = os.path.abspath(os.path.dirname(opt.template))
if opt.include_templates_dir and \
os.path.isdir(opt.include_templates_dir):
if opt.include_templates_dir and os.path.isdir(opt.include_templates_dir):
self.dirs['templates_include'] = os.path.abspath(opt.include_templates_dir)
if opt.policy_groups_dir and os.path.isdir(opt.policy_groups_dir):
self.dirs['policygroups'] = os.path.abspath(opt.policy_groups_dir)
if opt.include_policy_groups_dir and \
os.path.isdir(opt.include_policy_groups_dir):
if opt.include_policy_groups_dir and os.path.isdir(opt.include_policy_groups_dir):
self.dirs['policygroups_include'] = os.path.abspath(opt.include_policy_groups_dir)
self.policy_version = None
self.policy_vendor = None
if (opt.policy_version and not opt.policy_vendor) or \
(opt.policy_vendor and not opt.policy_version):
if ((opt.policy_version and not opt.policy_vendor)
or (opt.policy_vendor and not opt.policy_version)):
raise AppArmorException("Must specify both policy version and vendor")
# If specified --policy-version and --policy-vendor, use
@@ -560,8 +558,7 @@ class AppArmorEasyProfile:
attachment = ""
if binary:
if not valid_binary_path(binary):
raise AppArmorException("Invalid path for binary: '%s'" % \
binary)
raise AppArmorException("Invalid path for binary: '%s'" % binary)
if profile_name:
attachment = 'profile "%s" "%s"' % (profile_name, binary)
else:
@@ -713,8 +710,8 @@ class AppArmorEasyProfile:
d['security']['profiles'][pkey]['policy_vendor'] = self.policy_vendor
for key in params:
if key == 'profile_name' or \
(key == 'binary' and 'profile_name' not in params):
if (key == 'profile_name'
or (key == 'binary' and 'profile_name' not in params)):
continue # don't re-add the pkey
elif key == 'binary' and not params[key]:
continue # binary can by None when specifying --profile-name
@@ -769,24 +766,24 @@ def check_manifest_conflict_args(option, opt_str, value, parser):
'template_var']
for conflict in conflict_args:
if getattr(parser.values, conflict, False):
raise optparse.OptionValueError("can't use --%s with --manifest " \
"argument" % conflict)
raise optparse.OptionValueError(
"can't use --%s with --manifest argument" % conflict)
setattr(parser.values, option.dest, value)
def check_for_manifest_arg(option, opt_str, value, parser):
'''Check for -m/--manifest with conflicting args'''
if parser.values.manifest:
raise optparse.OptionValueError("can't use --%s with --manifest " \
"argument" % opt_str.lstrip('-'))
raise optparse.OptionValueError(
"can't use --%s with --manifest argument" % opt_str.lstrip('-'))
setattr(parser.values, option.dest, value)
def check_for_manifest_arg_append(option, opt_str, value, parser):
'''Check for -m/--manifest with conflicting args (with append)'''
if parser.values.manifest:
raise optparse.OptionValueError("can't use --%s with --manifest " \
"argument" % opt_str.lstrip('-'))
raise optparse.OptionValueError(
"can't use --%s with --manifest argument" % opt_str.lstrip('-'))
parser.values.ensure_value(option.dest, []).append(value)
@@ -1114,23 +1111,21 @@ def verify_options(opt, strict=False):
'''Make sure our options are valid'''
if hasattr(opt, 'binary') and opt.binary and not valid_path(opt.binary):
raise AppArmorException("Invalid binary '%s'" % opt.binary)
if hasattr(opt, 'profile_name') and opt.profile_name is not None and \
not valid_profile_name(opt.profile_name):
if (hasattr(opt, 'profile_name') and opt.profile_name is not None
and not valid_profile_name(opt.profile_name)):
raise AppArmorException("Invalid profile name '%s'" % opt.profile_name)
if hasattr(opt, 'binary') and opt.binary and \
hasattr(opt, 'profile_name') and opt.profile_name is not None and \
opt.profile_name.startswith('/'):
if (hasattr(opt, 'binary') and opt.binary
and hasattr(opt, 'profile_name') and opt.profile_name is not None
and opt.profile_name.startswith('/')):
raise AppArmorException("Profile name should not specify path with binary")
if hasattr(opt, 'policy_vendor') and opt.policy_vendor and \
not valid_policy_vendor(opt.policy_vendor):
raise AppArmorException("Invalid policy vendor '%s'" % \
opt.policy_vendor)
if hasattr(opt, 'policy_version') and opt.policy_version and \
not valid_policy_version(opt.policy_version):
raise AppArmorException("Invalid policy version '%s'" % \
opt.policy_version)
if hasattr(opt, 'template') and opt.template and \
not valid_template_name(opt.template, strict):
if (hasattr(opt, 'policy_vendor') and opt.policy_vendor
and not valid_policy_vendor(opt.policy_vendor)):
raise AppArmorException("Invalid policy vendor '%s'" % opt.policy_vendor)
if (hasattr(opt, 'policy_version') and opt.policy_version
and not valid_policy_version(opt.policy_version)):
raise AppArmorException("Invalid policy version '%s'" % opt.policy_version)
if (hasattr(opt, 'template') and opt.template
and not valid_template_name(opt.template, strict)):
raise AppArmorException("Invalid template '%s'" % opt.template)
if hasattr(opt, 'template_var') and opt.template_var:
for i in opt.template_var:
@@ -1167,8 +1162,8 @@ def verify_manifest(params, args=None):
if k in unsafe_keys:
err_str += "\nfound %s key" % k
elif k == 'profile_name':
if params['profile_name'].startswith('/') or \
'*' in params['profile_name']:
if (params['profile_name'].startswith('/')
or '*' in params['profile_name']):
err_str += "\nprofile_name '%s'" % params['profile_name']
elif k == 'abstractions':
for a in params['abstractions'].split(','):

View File

@@ -334,7 +334,6 @@ class BaseRuleset:
def _init_vars(self):
'''called by __init__() and delete_all_rules() - override in child class to initialize more variables'''
pass
def __repr__(self):
classname = self.__class__.__name__

View File

@@ -59,4 +59,3 @@ class AbiRule(IncludeRule):
class AbiRuleset(IncludeRuleset):
'''Class to handle and store a collection of abi rules'''
pass

View File

@@ -112,4 +112,3 @@ class AliasRule(BaseRule):
class AliasRuleset(BaseRuleset):
'''Class to handle and store a collection of alias rules'''
pass

View File

@@ -137,9 +137,9 @@ class ChangeProfileRule(BaseRule):
def is_covered_localvars(self, other_rule):
'''check if other_rule is covered by this rule object'''
if self.execmode != other_rule.execmode and \
(self.execmode not in ChangeProfileRule.equiv_execmodes or \
other_rule.execmode not in ChangeProfileRule.equiv_execmodes):
if (self.execmode != other_rule.execmode
and (self.execmode not in ChangeProfileRule.equiv_execmodes
or other_rule.execmode not in ChangeProfileRule.equiv_execmodes)):
return False
if not self._is_covered_plain(self.execcond, self.all_execconds, other_rule.execcond, other_rule.all_execconds, 'exec condition'):
@@ -158,9 +158,9 @@ class ChangeProfileRule(BaseRule):
if not type(rule_obj) == ChangeProfileRule:
raise AppArmorBug('Passed non-change_profile rule: %s' % str(rule_obj))
if self.execmode != rule_obj.execmode and \
(self.execmode not in ChangeProfileRule.equiv_execmodes or \
rule_obj.execmode not in ChangeProfileRule.equiv_execmodes):
if (self.execmode != rule_obj.execmode
and (self.execmode not in ChangeProfileRule.equiv_execmodes
or rule_obj.execmode not in ChangeProfileRule.equiv_execmodes)):
return False
if (self.execcond != rule_obj.execcond

View File

@@ -291,9 +291,9 @@ class FileRule(BaseRule):
# check exec_mode and target only if other_rule contains exec_perms (except ANY_EXEC) or link permissions
# (for mrwk permissions, the target is ignored anyway)
if (other_rule.exec_perms and other_rule.exec_perms != self.ANY_EXEC) or \
(other_rule.perms and 'l' in other_rule.perms) or \
(other_rule.perms and 'link' in other_rule.perms):
if ((other_rule.exec_perms and other_rule.exec_perms != self.ANY_EXEC)
or (other_rule.perms and 'l' in other_rule.perms)
or (other_rule.perms and 'link' in other_rule.perms)):
if not self._is_covered_aare(self.target, self.all_targets, other_rule.target, other_rule.all_targets, 'target'):
return False

View File

@@ -257,7 +257,7 @@ class SandboxXserver():
raise AppArmorException("Could not find available X display")
# Use dedicated .Xauthority file
xauth = os.path.join(os.path.expanduser('~'), \
xauth = os.path.join(os.path.expanduser('~'),
'.Xauthority-sandbox%s' % display.split(':')[1])
return display, xauth
@@ -294,11 +294,13 @@ class SandboxXserver():
if rc != 0:
raise AppArmorException("Could not generate magic cookie")
rc, out = cmd(('xauth', '-f', self.xauth, \
'add', \
self.display, \
'MIT-MAGIC-COOKIE-1', \
cookie.strip()))
rc, out = cmd(
('xauth', '-f', self.xauth,
'add',
self.display,
'MIT-MAGIC-COOKIE-1',
cookie.strip())
)
if rc != 0:
raise AppArmorException("Could not generate '%s'" % self.display)
@@ -605,7 +607,7 @@ EndSection
started = False
# We need to wait for the xpra socket to exist before attaching
fn = os.path.join(os.environ['HOME'], '.xpra', '%s-%s' % \
fn = os.path.join(os.environ['HOME'], '.xpra', '%s-%s' %
(socket.gethostname(), self.display.split(':')[1]))
for i in range(self.timeout * 2): # up to self.timeout seconds to start
if os.path.exists(fn):

View File

@@ -32,7 +32,6 @@ class AATest(unittest.TestCase):
def AASetup(self):
'''override this function if a test needs additional setup steps (instead of overriding setUp())'''
pass
def tearDown(self):
if self.tmpdir and os.path.exists(self.tmpdir):
@@ -42,7 +41,6 @@ class AATest(unittest.TestCase):
def AATeardown(self):
'''override this function if a test needs additional teardown steps (instead of overriding tearDown())'''
pass
def createTmpdir(self):
self.tmpdir = tempfile.mkdtemp(prefix='aa-test-')
@@ -64,7 +62,7 @@ class AAParseTest(unittest.TestCase):
parsed = self.parse_function(rule)
self.assertEqual(
rule, parsed.serialize(),
'parse object %s returned "%s", expected "%s"' \
'parse object %s returned "%s", expected "%s"'
% (self.parse_function.__doc__, parsed.serialize(), rule))

View File

@@ -705,7 +705,7 @@ POLICYGROUPS_DIR="%s/templates"
except InterceptedError:
raised = True
self.assertTrue(raised, msg="%s and manifest arguments did not " \
self.assertTrue(raised, msg="%s and manifest arguments did not "
"raise a parse error" % opt)
# manifest first
@@ -717,7 +717,7 @@ POLICYGROUPS_DIR="%s/templates"
except InterceptedError:
raised = True
self.assertTrue(raised, msg="%s and manifest arguments did not " \
self.assertTrue(raised, msg="%s and manifest arguments did not "
"raise a parse error" % opt)
def test_manifest_conflicts_profilename(self):
@@ -2253,12 +2253,12 @@ POLICYGROUPS_DIR="%s/templates"
tdir = os.path.join(self.tmpdir, 'templates', policy_subdir)
for t in easyp.get_templates():
self.assertTrue(t.startswith(tdir), \
self.assertTrue(t.startswith(tdir),
"'%s' does not start with '%s'" % (t, tdir))
pdir = os.path.join(self.tmpdir, 'policygroups', policy_subdir)
for p in easyp.get_policy_groups():
self.assertTrue(p.startswith(pdir), \
self.assertTrue(p.startswith(pdir),
"'%s' does not start with '%s'" % (p, pdir))
params = easyprof.gen_policy_params(self.binary, self.options)