Merge lp:~sbeattie/apparmor-profile-tools/pre-merger-cleanups into lp:apparmor-profile-tools

Proposed by Steve Beattie on 2014-02-11
Status: Merged
Merge reported by: Steve Beattie
Merged at revision: not available
Proposed branch: lp:~sbeattie/apparmor-profile-tools/pre-merger-cleanups
Merge into: lp:apparmor-profile-tools
Diff against target: 2957 lines (+481/-465)
20 files modified
Tools/aa-audit (+4/-3)
Tools/aa-autodep (+5/-4)
Tools/aa-cleanprof (+5/-4)
Tools/aa-complain (+4/-3)
Tools/aa-disable (+4/-3)
Tools/aa-enforce (+4/-3)
Tools/aa-genprof (+4/-3)
Tools/aa-logprof (+4/-3)
Tools/aa-mergeprof (+4/-3)
Tools/aa-unconfined (+4/-3)
apparmor/__init__.py (+0/-15)
apparmor/aa.py (+310/-284)
apparmor/aamode.py (+9/-9)
apparmor/common.py (+11/-19)
apparmor/config.py (+7/-7)
apparmor/logparser.py (+31/-27)
apparmor/severity.py (+18/-19)
apparmor/tools.py (+26/-21)
apparmor/ui.py (+27/-31)
apparmor/yasti.py (+0/-1)
To merge this branch: bzr merge lp:~sbeattie/apparmor-profile-tools/pre-merger-cleanups
Reviewer Review Type Date Requested Status
Kshitij Gupta 2014-02-11 Pending
Review via email: mp+205701@code.launchpad.net

Description of the change

Here are some simple cleanups in preparation for merging the new profile tools into trunk.

To post a comment you must log in.
Christian Boltz (cboltz) wrote :

Hello,

Am Dienstag, 11. Februar 2014 schrieb Steve Beattie:
> Steve Beattie has proposed merging
> lp:~sbeattie/apparmor-profile-tools/pre-merger-cleanups into
> lp:apparmor-profile-tools.
>
> Requested reviews:
> Kshitij Gupta (kgupta8592)
>
> For more details, see:
> https://code.launchpad.net/~sbeattie/apparmor-profile-tools/pre-merger
> -cleanups/+merge/205701
>
> Here are some simple cleanups in preparation for merging the new
> profile tools into trunk.

I had a look at the changes (hint: they are easier to read if you check
the individual commits, for example via the "For more details" link
above - for the pep8 commit, you might want to ignore whitespace
changes) and they all look good.

The only detail I don't like too much is that the changed translation
handling adds some lines to all aa-* tools - but that's something we
should fix with one of the next commits.

To sum it up: Kshitij, IMHO you can merge this :-)
or to say it in a more formal way:
Acked-by: Christian Boltz <email address hidden>

I'd recommend to merge it _before_ commiting my patches - Steve's
changes affect more lines, which also means the risk of merge conflicts
is quite big if you commit my patches first.

Regards,

Christian Boltz
--
Unix: Alles ist ein File, und was kein File ist, hat sich gefaelligst
als ein solches zu tarnen. [Wolfgang Weisselberg in linux-liste]

100. By Steve Beattie on 2014-02-12

Simplify the work tools and modules need to do to get the shared
translations. External utilities can still use their own textdomains
if they have strings that are not part of the apparmor-utils catalog.

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== modified file 'Tools/aa-audit'
2--- Tools/aa-audit 2014-02-01 01:34:08 +0000
3+++ Tools/aa-audit 2014-02-12 00:39:55 +0000
4@@ -15,11 +15,12 @@
5 import argparse
6 import traceback
7
8-from apparmor.common import init_translations
9-init_translations()
10-
11 import apparmor.tools
12
13+# setup module translations
14+from apparmor.translations import init_translation
15+_ = init_translation()
16+
17 parser = argparse.ArgumentParser(description=_('Switch the given programs to audit mode'))
18 parser.add_argument('-d', '--dir', type=str, help=_('path to profiles'))
19 parser.add_argument('-r', '--remove', action='store_true', help=_('remove audit mode'))
20
21=== modified file 'Tools/aa-autodep'
22--- Tools/aa-autodep 2013-10-21 21:36:23 +0000
23+++ Tools/aa-autodep 2014-02-12 00:39:55 +0000
24@@ -14,11 +14,12 @@
25 # ----------------------------------------------------------------------
26 import argparse
27
28-from apparmor.common import init_translations
29-init_translations()
30-
31 import apparmor.tools
32
33+# setup module translations
34+from apparmor.translations import init_translation
35+_ = init_translation()
36+
37 parser = argparse.ArgumentParser(description=_('Generate a basic AppArmor profile by guessing requirements'))
38 parser.add_argument('--force', type=str, help=_('overwrite existing profile'))
39 parser.add_argument('-d', '--dir', type=str, help=_('path to profiles'))
40@@ -27,4 +28,4 @@
41
42 autodep = apparmor.tools.aa_tools('autodep', args)
43
44-autodep.act()
45\ No newline at end of file
46+autodep.act()
47
48=== modified file 'Tools/aa-cleanprof'
49--- Tools/aa-cleanprof 2013-10-21 21:36:23 +0000
50+++ Tools/aa-cleanprof 2014-02-12 00:39:55 +0000
51@@ -14,11 +14,12 @@
52 # ----------------------------------------------------------------------
53 import argparse
54
55-from apparmor.common import init_translations
56-init_translations()
57-
58 import apparmor.tools
59
60+# setup module translations
61+from apparmor.translations import init_translation
62+_ = init_translation()
63+
64 parser = argparse.ArgumentParser(description=_('Cleanup the profiles for the given programs'))
65 parser.add_argument('-d', '--dir', type=str, help=_('path to profiles'))
66 parser.add_argument('program', type=str, nargs='+', help=_('name of program'))
67@@ -27,4 +28,4 @@
68
69 clean = apparmor.tools.aa_tools('cleanprof', args)
70
71-clean.act()
72\ No newline at end of file
73+clean.act()
74
75=== modified file 'Tools/aa-complain'
76--- Tools/aa-complain 2013-12-29 09:42:30 +0000
77+++ Tools/aa-complain 2014-02-12 00:39:55 +0000
78@@ -14,11 +14,12 @@
79 # ----------------------------------------------------------------------
80 import argparse
81
82-from apparmor.common import init_translations
83-init_translations()
84-
85 import apparmor.tools
86
87+# setup module translations
88+from apparmor.translations import init_translation
89+_ = init_translation()
90+
91 parser = argparse.ArgumentParser(description=_('Switch the given program to complain mode'))
92 parser.add_argument('-d', '--dir', type=str, help=_('path to profiles'))
93 parser.add_argument('-r', '--remove', action='store_true', help=_('remove complain mode'))
94
95=== modified file 'Tools/aa-disable'
96--- Tools/aa-disable 2013-10-21 21:36:23 +0000
97+++ Tools/aa-disable 2014-02-12 00:39:55 +0000
98@@ -14,11 +14,12 @@
99 # ----------------------------------------------------------------------
100 import argparse
101
102-from apparmor.common import init_translations
103-init_translations()
104-
105 import apparmor.tools
106
107+# setup module translations
108+from apparmor.translations import init_translation
109+_ = init_translation()
110+
111 parser = argparse.ArgumentParser(description=_('Disable the profile for the given programs'))
112 parser.add_argument('-d', '--dir', type=str, help=_('path to profiles'))
113 parser.add_argument('-r', '--revert', action='store_true', help=_('enable the profile for the given programs'))
114
115=== modified file 'Tools/aa-enforce'
116--- Tools/aa-enforce 2013-10-21 21:36:23 +0000
117+++ Tools/aa-enforce 2014-02-12 00:39:55 +0000
118@@ -14,11 +14,12 @@
119 # ----------------------------------------------------------------------
120 import argparse
121
122-from apparmor.common import init_translations
123-init_translations()
124-
125 import apparmor.tools
126
127+# setup module translations
128+from apparmor.translations import init_translation
129+_ = init_translation()
130+
131 parser = argparse.ArgumentParser(description=_('Switch the given program to enforce mode'))
132 parser.add_argument('-d', '--dir', type=str, help=_('path to profiles'))
133 parser.add_argument('-r', '--remove', action='store_true', help=_('switch to complain mode'))
134
135=== modified file 'Tools/aa-genprof'
136--- Tools/aa-genprof 2013-12-29 09:42:30 +0000
137+++ Tools/aa-genprof 2014-02-12 00:39:55 +0000
138@@ -19,11 +19,12 @@
139 import subprocess
140 import sys
141
142-from apparmor.common import init_translations
143-init_translations()
144-
145 import apparmor.aa as apparmor
146
147+# setup module translations
148+from apparmor.translations import init_translation
149+_ = init_translation()
150+
151 def sysctl_read(path):
152 value = None
153 with open(path, 'r') as f_in:
154
155=== modified file 'Tools/aa-logprof'
156--- Tools/aa-logprof 2013-12-29 09:42:30 +0000
157+++ Tools/aa-logprof 2014-02-12 00:39:55 +0000
158@@ -15,11 +15,12 @@
159 import argparse
160 import os
161
162-from apparmor.common import init_translations
163-init_translations()
164-
165 import apparmor.aa as apparmor
166
167+# setup module translations
168+from apparmor.translations import init_translation
169+_ = init_translation()
170+
171 parser = argparse.ArgumentParser(description=_('Process log entries to generate profiles'))
172 parser.add_argument('-d', '--dir', type=str, help=_('path to profiles'))
173 parser.add_argument('-f', '--file', type=str, help=_('path to logfile'))
174
175=== modified file 'Tools/aa-mergeprof'
176--- Tools/aa-mergeprof 2013-10-21 21:36:23 +0000
177+++ Tools/aa-mergeprof 2014-02-12 00:39:55 +0000
178@@ -15,14 +15,15 @@
179 import argparse
180 import sys
181
182-from apparmor.common import init_translations
183-init_translations()
184-
185 import apparmor.aa
186 import apparmor.aamode
187 import apparmor.severity
188 import apparmor.cleanprofile as cleanprofile
189
190+# setup module translations
191+from apparmor.translations import init_translation
192+_ = init_translation()
193+
194 parser = argparse.ArgumentParser(description=_('Perform a 3way merge on the given profiles'))
195 parser.add_argument('mine', type=str, help=_('your profile'))
196 parser.add_argument('base', type=str, help=_('base profile'))
197
198=== modified file 'Tools/aa-unconfined'
199--- Tools/aa-unconfined 2013-12-29 09:42:30 +0000
200+++ Tools/aa-unconfined 2014-02-12 00:39:55 +0000
201@@ -17,11 +17,12 @@
202 import re
203 import sys
204
205-from apparmor.common import init_translations
206-init_translations()
207-
208 import apparmor.aa as apparmor
209
210+# setup module translations
211+from apparmor.translations import init_translation
212+_ = init_translation()
213+
214 parser = argparse.ArgumentParser(description=_("Lists unconfined processes having tcp or udp ports"))
215 parser.add_argument("--paranoid", action="store_true", help=_("scan all processes from /proc"))
216 args = parser.parse_args()
217
218=== modified file 'apparmor/__init__.py'
219--- apparmor/__init__.py 2013-12-19 21:42:58 +0000
220+++ apparmor/__init__.py 2014-02-12 00:39:55 +0000
221@@ -1,24 +1,9 @@
222 # ------------------------------------------------------------------
223 #
224 # Copyright (C) 2011-2012 Canonical Ltd.
225-# Copyright (C) 2013 Kshitij Gupta <kgupta8592@gmail.com>
226 #
227 # This program is free software; you can redistribute it and/or
228 # modify it under the terms of version 2 of the GNU General Public
229 # License published by the Free Software Foundation.
230 #
231 # ------------------------------------------------------------------
232-import gettext
233-import locale
234-
235-def init_localisation():
236- locale.setlocale(locale.LC_ALL, '')
237- #If a correct locale has been provided set filename else let an IOError be raised
238- filename = '/usr/share/locale/%s/LC_MESSAGES/apparmor-utils.mo' % locale.getlocale()[0]
239- try:
240- trans = gettext.GNUTranslations(open(filename, 'rb'))
241- except IOError:
242- trans = gettext.NullTranslations()
243- trans.install()
244-
245-init_localisation()
246
247=== modified file 'apparmor/aa.py'
248--- apparmor/aa.py 2014-02-01 00:44:05 +0000
249+++ apparmor/aa.py 2014-02-12 00:39:55 +0000
250@@ -13,11 +13,11 @@
251 # ----------------------------------------------------------------------
252 # No old version logs, only 2.6 + supported
253 from __future__ import with_statement
254+import gettext
255 import inspect
256 import os
257 import re
258 import shutil
259-import stat
260 import subprocess
261 import sys
262 import time
263@@ -33,12 +33,20 @@
264 from copy import deepcopy
265
266 from apparmor.common import (AppArmorException, error, debug, msg, cmd,
267- open_file_read, valid_path,
268- hasher, open_file_write, convert_regexp, DebugLogger)
269-
270-from apparmor.ui import *
271-
272-from apparmor.aamode import *
273+ open_file_read, valid_path, hasher,
274+ open_file_write, convert_regexp, DebugLogger)
275+
276+import apparmor.ui as aaui
277+
278+from apparmor.aamode import (str_to_mode, mode_to_str, contains, split_mode,
279+ mode_to_str_user, mode_contains, AA_OTHER,
280+ flatten_mode, owner_flatten_mode)
281+
282+from apparmor.yasti import SendDataToYast, GetDataFromYast, shutdown_yast
283+
284+# setup module translations
285+from apparmor.translations import init_translation
286+_ = init_translation()
287
288 # Setup logging incase of debugging is enabled
289 debug_logger = DebugLogger('aa')
290@@ -67,7 +75,7 @@
291
292 existing_profiles = dict()
293
294-seen_events = 0 # was our
295+seen_events = 0 # was our
296 # To store the globs entered by users so they can be provided again
297 user_globs = []
298
299@@ -76,7 +84,7 @@
300 t = hasher() # dict()
301 transitions = hasher()
302 aa = hasher() # Profiles originally in sd, replace by aa
303-original_aa = hasher()
304+original_aa = hasher()
305 extras = hasher() # Inactive profiles from extras
306 ### end our
307 log = []
308@@ -85,11 +93,11 @@
309 seen = hasher() # dir()
310 profile_changes = hasher()
311 prelog = hasher()
312-log_dict = hasher()#dict()
313+log_dict = hasher() # dict()
314 changed = dict()
315 created = []
316 skip = hasher()
317-helpers = dict() # Preserve this between passes # was our
318+helpers = dict() # Preserve this between passes # was our
319 ### logprof ends
320
321 filelist = hasher() # File level variables and stuff in config files
322@@ -110,7 +118,7 @@
323 return False
324 size = os.stat(file).st_size
325 # Limit to checking files under 100k for the sake of speed
326- if size >100000:
327+ if size > 100000:
328 return False
329 with open_file_read(file, encoding='ascii') as f_in:
330 for line in f_in:
331@@ -128,11 +136,11 @@
332 caller = inspect.stack()[1][3]
333
334 # If caller is SendDataToYast or GetDatFromYast simply exit
335- if caller == 'SendDataToYast' or caller== 'GetDatFromYast':
336+ if caller == 'SendDataToYast' or caller == 'GetDatFromYast':
337 sys.exit(1)
338
339 # Else tell user what happened
340- UI_Important(message)
341+ aaui.UI_Important(message)
342 shutdown_yast()
343 sys.exit(1)
344
345@@ -164,7 +172,7 @@
346
347 def which(file):
348 """Returns the executable fullpath for the file, None otherwise"""
349- if sys.version_info >= (3,3):
350+ if sys.version_info >= (3, 3):
351 return shutil.which(file)
352 env_dirs = os.getenv('PATH').split(':')
353 for env_dir in env_dirs:
354@@ -238,33 +246,33 @@
355 def complain(path):
356 """Sets the profile to complain mode if it exists"""
357 prof_filename, name = name_to_prof_filename(path)
358- if not prof_filename :
359+ if not prof_filename:
360 fatal_error(_("Can't find %s") % path)
361 set_complain(prof_filename, name)
362
363 def enforce(path):
364 """Sets the profile to enforce mode if it exists"""
365 prof_filename, name = name_to_prof_filename(path)
366- if not prof_filename :
367+ if not prof_filename:
368 fatal_error(_("Can't find %s") % path)
369 set_enforce(prof_filename, name)
370
371 def set_complain(filename, program):
372 """Sets the profile to complain mode"""
373- UI_Info(_('Setting %s to complain mode.') % program)
374+ aaui.UI_Info(_('Setting %s to complain mode.') % program)
375 create_symlink('force-complain', filename)
376 change_profile_flags(filename, program, 'complain', True)
377
378 def set_enforce(filename, program):
379 """Sets the profile to enforce mode"""
380- UI_Info(_('Setting %s to enforce mode.') % program)
381+ aaui.UI_Info(_('Setting %s to enforce mode.') % program)
382 delete_symlink('force-complain', filename)
383 delete_symlink('disable', filename)
384 change_profile_flags(filename, program, 'complain', False)
385
386 def delete_symlink(subdir, filename):
387 path = filename
388- link = re.sub('^%s'%profile_dir, '%s/%s'%(profile_dir, subdir), path)
389+ link = re.sub('^%s' % profile_dir, '%s/%s' % (profile_dir, subdir), path)
390 if link != path and os.path.islink(link):
391 os.remove(link)
392
393@@ -272,13 +280,13 @@
394 path = filename
395 bname = os.path.basename(filename)
396 if not bname:
397- raise AppArmorException(_('Unable to find basename for %s.')%filename)
398+ raise AppArmorException(_('Unable to find basename for %s.') % filename)
399 #print(filename)
400- link = re.sub('^%s'%profile_dir, '%s/%s'%(profile_dir, subdir), path)
401+ link = re.sub('^%s' % profile_dir, '%s/%s' % (profile_dir, subdir), path)
402 #print(link)
403 #link = link + '/%s'%bname
404 #print(link)
405- symlink_dir=os.path.dirname(link)
406+ symlink_dir = os.path.dirname(link)
407 if not os.path.exists(symlink_dir):
408 # If the symlink directory does not exist create it
409 os.makedirs(symlink_dir)
410@@ -287,7 +295,7 @@
411 try:
412 os.symlink(filename, link)
413 except:
414- raise AppArmorException(_('Could not create %s symlink to %s.')%(link, filename))
415+ raise AppArmorException(_('Could not create %s symlink to %s.') % (link, filename))
416
417 def head(file):
418 """Returns the first/head line of the file"""
419@@ -300,7 +308,7 @@
420 pass
421 return first
422 else:
423- raise AppArmorException(_('Unable to read first line from %s: File Not Found') %file)
424+ raise AppArmorException(_('Unable to read first line from %s: File Not Found') % file)
425
426 def get_output(params):
427 """Returns the return code output by running the program with the args given in the list"""
428@@ -314,7 +322,7 @@
429 # Get the output of the program
430 output = subprocess.check_output(params)
431 except OSError as e:
432- raise AppArmorException(_("Unable to fork: %s\n\t%s") %(program, str(e)))
433+ raise AppArmorException(_("Unable to fork: %s\n\t%s") % (program, str(e)))
434 # If exit-codes besides 0
435 except subprocess.CalledProcessError as e:
436 output = e.output
437@@ -419,7 +427,7 @@
438
439 created.append(localfile)
440 changed.append(localfile)
441-
442+
443 debug_logger.debug("Profile for %s:\n\t%s" % (localfile, local_profile.__str__()))
444 return {localfile: local_profile}
445
446@@ -434,9 +442,9 @@
447 #prof_unload(local_prof)
448
449 def confirm_and_abort():
450- ans = UI_YesNo(_('Are you sure you want to abandon this set of profile changes and exit?'), 'n')
451+ ans = aaui.UI_YesNo(_('Are you sure you want to abandon this set of profile changes and exit?'), 'n')
452 if ans == 'y':
453- UI_Info(_('Abandoning all changes.'))
454+ aaui.UI_Info(_('Abandoning all changes.'))
455 shutdown_yast()
456 for prof in created:
457 delete_profile(prof)
458@@ -449,13 +457,13 @@
459 local_profiles = []
460 profile_hash = hasher()
461 if repo_is_enabled():
462- UI_BusyStart(_('Connecting to repository...'))
463+ aaui.UI_BusyStart(_('Connecting to repository...'))
464 status_ok, ret = fetch_profiles_by_name(repo_url, distro, prof_name)
465- UI_BusyStop()
466+ aaui.UI_BusyStop()
467 if status_ok:
468 profile_hash = ret
469 else:
470- UI_Important(_('WARNING: Error fetching profiles from the repository'))
471+ aaui.UI_Important(_('WARNING: Error fetching profiles from the repository'))
472 inactive_profile = get_inactive_profile(prof_name)
473 if inactive_profile:
474 uname = 'Inactive local profile for %s' % prof_name
475@@ -493,13 +501,12 @@
476
477 ans = ''
478 while 'CMD_USE_PROFILE' not in ans and 'CMD_CREATE_PROFILE' not in ans:
479- ans, arg = UI_PromptUser(q)
480+ ans, arg = aaui.UI_PromptUser(q)
481 p = profile_hash[options[arg]]
482 q['selected'] = options.index(options[arg])
483 if ans == 'CMD_VIEW_PROFILE':
484- if UI_mode == 'yast':
485- SendDataToYast({
486- 'type': 'dialogue-view-profile',
487+ if aaui.UI_mode == 'yast':
488+ SendDataToYast({'type': 'dialogue-view-profile',
489 'user': options[arg],
490 'profile': p['profile'],
491 'profile_type': p['profile_type']
492@@ -530,7 +537,7 @@
493 if complain:
494 fname = get_profile_filename(pname)
495 set_profile_flags(profile_dir + fname, 'complain')
496- UI_Info(_('Setting %s to complain mode.') % pname)
497+ aaui.UI_Info(_('Setting %s to complain mode.') % pname)
498 except Exception as e:
499 sys.stderr.write(_("Error activating profiles: %s") % e)
500
501@@ -585,7 +592,7 @@
502 if profile == program:
503 return flags
504
505- raise AppArmorException(_('%s contains no profile')%filename)
506+ raise AppArmorException(_('%s contains no profile') % filename)
507
508 def change_profile_flags(filename, program, flag, set_flag):
509 old_flags = get_profile_flags(filename, program)
510@@ -595,7 +602,7 @@
511 # Flags maybe white-space and/or , separated
512 old_flags = old_flags.split(',')
513
514- if type(old_flags) == type([]):
515+ if not isinstance(old_flags, str):
516 for i in old_flags:
517 newflags += i.split()
518 else:
519@@ -619,7 +626,7 @@
520 regex_hat_flag = re.compile('^([a-z]*)\s+([A-Z]*)\s*(#.*)?$')
521 if os.path.isfile(prof_filename):
522 with open_file_read(prof_filename) as f_in:
523- temp_file = tempfile.NamedTemporaryFile('w', prefix=prof_filename , suffix='~', delete=False, dir=profile_dir)
524+ temp_file = tempfile.NamedTemporaryFile('w', prefix=prof_filename, suffix='~', delete=False, dir=profile_dir)
525 shutil.copymode(prof_filename, temp_file.name)
526 with open_file_write(temp_file.name) as f_out:
527 for line in f_in:
528@@ -679,7 +686,7 @@
529 if not status_ok:
530 if not ret:
531 ret = 'UNKNOWN ERROR'
532- UI_Important(_('WARNING: Error synchronizing profiles with the repository:\n%s\n') % ret)
533+ aaui.UI_Important(_('WARNING: Error synchronizing profiles with the repository:\n%s\n') % ret)
534 else:
535 users_repo_profiles = ret
536 serialize_opts['NO_FLAGS'] = True
537@@ -717,7 +724,7 @@
538 else:
539 if not ret:
540 ret = 'UNKNOWN ERROR'
541- UI_Important(_('WARNING: Error synchronizing profiles with the repository\n%s') % ret)
542+ aaui.UI_Important(_('WARNING: Error synchronizing profiles with the repository\n%s') % ret)
543 continue
544 if p_repo != p_local:
545 changed_profiles.append(prof)
546@@ -743,7 +750,7 @@
547 def submit_created_profiles(new_profiles):
548 #url = cfg['repository']['url']
549 if new_profiles:
550- if UI_mode == 'yast':
551+ if aaui.UI_mode == 'yast':
552 title = 'New Profiles'
553 message = 'Please select the newly created profiles that you would like to store in the repository'
554 yast_select_and_upload_profiles(title, message, new_profiles)
555@@ -755,7 +762,7 @@
556 def submit_changed_profiles(changed_profiles):
557 #url = cfg['repository']['url']
558 if changed_profiles:
559- if UI_mode == 'yast':
560+ if aaui.UI_mode == 'yast':
561 title = 'Changed Profiles'
562 message = 'Please select which of the changed profiles would you like to upload to the repository'
563 yast_select_and_upload_profiles(title, message, changed_profiles)
564@@ -770,8 +777,7 @@
565 profs = profiles_up[:]
566 for p in profs:
567 profile_changes[p[0]] = get_profile_diff(p[2], p[1])
568- SendDataToYast({
569- 'type': 'dialog-select-profiles',
570+ SendDataToYast({'type': 'dialog-select-profiles',
571 'title': title,
572 'explanation': message,
573 'default_select': 'false',
574@@ -806,8 +812,8 @@
575 else:
576 if not ret:
577 ret = 'UNKNOWN ERROR'
578- UI_Important(_('WARNING: An error occurred while uploading the profile %s\n%s') % (p, ret))
579- UI_Info(_('Uploaded changes to repository.'))
580+ aaui.UI_Important(_('WARNING: An error occurred while uploading the profile %s\n%s') % (p, ret))
581+ aaui.UI_Info(_('Uploaded changes to repository.'))
582 if yarg.get('NEVER_ASK_AGAIN'):
583 unselected_profiles = []
584 for p in profs:
585@@ -833,13 +839,13 @@
586 q['selected'] = 0
587 ans = ''
588 while 'CMD_UPLOAD_CHANGES' not in ans and 'CMD_ASK_NEVER' not in ans and 'CMD_ASK_LATER' not in ans:
589- ans, arg = UI_PromptUser(q)
590+ ans, arg = aaui.UI_PromptUser(q)
591 if ans == 'CMD_VIEW_CHANGES':
592 display_changes(profs[arg][2], profs[arg][1])
593 if ans == 'CMD_NEVER_ASK':
594 set_profiles_local_only([i[0] for i in profs])
595 elif ans == 'CMD_UPLOAD_CHANGES':
596- changelog = UI_GetString(_('Changelog Entry: '), '')
597+ changelog = aaui.UI_GetString(_('Changelog Entry: '), '')
598 user, passw = get_repo_user_pass()
599 if user and passw:
600 for p_data in profs:
601@@ -847,19 +853,19 @@
602 prof_string = p_data[1]
603 status_ok, ret = upload_profile(url, user, passw,
604 cfg['repository']['distro'],
605- prof, prof_string, changelog )
606+ prof, prof_string, changelog)
607 if status_ok:
608 newprof = ret
609 newid = newprof['id']
610 set_repo_info(aa[prof][prof], url, user, newid)
611 write_profile_ui_feedback(prof)
612- UI_Info('Uploaded %s to repository' % prof)
613+ aaui.UI_Info('Uploaded %s to repository' % prof)
614 else:
615 if not ret:
616 ret = 'UNKNOWN ERROR'
617- UI_Important(_('WARNING: An error occurred while uploading the profile %s\n%s') % (prof, ret))
618+ aaui.UI_Important(_('WARNING: An error occurred while uploading the profile %s\n%s') % (prof, ret))
619 else:
620- UI_Important(_('Repository Error\nRegistration or Signin was unsuccessful. User login\ninformation is required to upload profiles to the repository.\nThese changes could not be sent.'))
621+ aaui.UI_Important(_('Repository Error\nRegistration or Signin was unsuccessful. User login\ninformation is required to upload profiles to the repository.\nThese changes could not be sent.'))
622
623 def set_profiles_local_only(profs):
624 for p in profs:
625@@ -886,7 +892,7 @@
626 ret_list.append('CMD_EXEC_IX_OFF')
627 if 'u' in options:
628 ret_list.append('CMD_ux')
629-
630+
631 else:
632 if 'i' in options:
633 ret_list.append('CMD_ix')
634@@ -985,7 +991,7 @@
635
636 seen_events += 1
637
638- ans = UI_PromptUser(q)
639+ ans = aaui.UI_PromptUser(q)
640
641 transitions[context] = ans
642
643@@ -1043,7 +1049,7 @@
644 else:
645 do_execute = True
646
647- if mode & AA_MAY_LINK:
648+ if mode & apparmor.aamode.AA_MAY_LINK:
649 regex_link = re.compile('^from (.+) to (.+)$')
650 match = regex_link.search(detail)
651 if match:
652@@ -1090,7 +1096,7 @@
653 combinedaudit = set()
654 ## Check return Value Consistency
655 # Check if path matches any existing regexps in profile
656- cm, am , m = rematchfrag(aa[profile][hat], 'allow', exec_target)
657+ cm, am, m = rematchfrag(aa[profile][hat], 'allow', exec_target)
658 if cm:
659 combinedmode |= cm
660 if am:
661@@ -1202,7 +1208,7 @@
662 default = None
663 if 'p' in options and os.path.exists(get_profile_filename(exec_target)):
664 default = 'CMD_px'
665- sys.stdout.write(_('Target profile exists: %s\n') %get_profile_filename(exec_target))
666+ sys.stdout.write(_('Target profile exists: %s\n') % get_profile_filename(exec_target))
667 elif 'i' in options:
668 default = 'CMD_ix'
669 elif 'c' in options:
670@@ -1241,7 +1247,7 @@
671
672 ans = ''
673 while not regex_options.search(ans):
674- ans = UI_PromptUser(q)[0].strip()
675+ ans = aaui.UI_PromptUser(q)[0].strip()
676 if ans.startswith('CMD_EXEC_IX_'):
677 exec_toggle = not exec_toggle
678 q['functions'] = []
679@@ -1252,7 +1258,7 @@
680 arg = exec_target
681 ynans = 'n'
682 if profile == hat:
683- ynans = UI_YesNo(_('Are you specifying a transition to a local profile?'), 'n')
684+ ynans = aaui.UI_YesNo(_('Are you specifying a transition to a local profile?'), 'n')
685 if ynans == 'y':
686 if ans == 'CMD_nx':
687 ans = 'CMD_cx'
688@@ -1264,7 +1270,7 @@
689 else:
690 ans = 'CMD_pix'
691
692- to_name = UI_GetString(_('Enter profile name to transition to: '), arg)
693+ to_name = aaui.UI_GetString(_('Enter profile name to transition to: '), arg)
694
695 regex_optmode = re.compile('CMD_(px|cx|nx|pix|cix|nix)')
696 if ans == 'CMD_ix':
697@@ -1277,18 +1283,18 @@
698 if parent_uses_ld_xxx:
699 px_msg = _("Should AppArmor sanitise the environment when\nswitching profiles?\n\nSanitising environment is more secure,\nbut this application appears to be using LD_PRELOAD\nor LD_LIBRARY_PATH and sanitising the environment\ncould cause functionality problems.")
700
701- ynans = UI_YesNo(px_msg, px_default)
702+ ynans = aaui.UI_YesNo(px_msg, px_default)
703 if ynans == 'y':
704 # Disable the unsafe mode
705- exec_mode = exec_mode - (AA_EXEC_UNSAFE | AA_OTHER(AA_EXEC_UNSAFE))
706+ exec_mode = exec_mode - (apparmor.aamode.AA_EXEC_UNSAFE | AA_OTHER(apparmor.aamode.AA_EXEC_UNSAFE))
707 elif ans == 'CMD_ux':
708 exec_mode = str_to_mode('ux')
709- ynans = UI_YesNo(_("Launching processes in an unconfined state is a very\ndangerous operation and can cause serious security holes.\n\nAre you absolutely certain you wish to remove all\nAppArmor protection when executing %s ?") % exec_target, 'n')
710+ ynans = aaui.UI_YesNo(_("Launching processes in an unconfined state is a very\ndangerous operation and can cause serious security holes.\n\nAre you absolutely certain you wish to remove all\nAppArmor protection when executing %s ?") % exec_target, 'n')
711 if ynans == 'y':
712- ynans = UI_YesNo(_("Should AppArmor sanitise the environment when\nrunning this program unconfined?\n\nNot sanitising the environment when unconfining\na program opens up significant security holes\nand should be avoided if at all possible."), 'y')
713+ ynans = aaui.UI_YesNo(_("Should AppArmor sanitise the environment when\nrunning this program unconfined?\n\nNot sanitising the environment when unconfining\na program opens up significant security holes\nand should be avoided if at all possible."), 'y')
714 if ynans == 'y':
715 # Disable the unsafe mode
716- exec_mode = exec_mode - (AA_EXEC_UNSAFE | AA_OTHER(AA_EXEC_UNSAFE))
717+ exec_mode = exec_mode - (apparmor.aamode.AA_EXEC_UNSAFE | AA_OTHER(apparmor.aamode.AA_EXEC_UNSAFE))
718 else:
719 ans = 'INVALID'
720 transitions[context_new] = ans
721@@ -1345,7 +1351,7 @@
722
723 if ans == 'CMD_ix':
724 if hat:
725- profile_changes[pid] = '%s//%s' %(profile, hat)
726+ profile_changes[pid] = '%s//%s' % (profile, hat)
727 else:
728 profile_changes[pid] = '%s//' % profile
729 elif re.search('^CMD_(px|nx|pix|nix)', ans):
730@@ -1361,7 +1367,7 @@
731 if not os.path.exists(get_profile_filename(exec_target)):
732 ynans = 'y'
733 if exec_mode & str_to_mode('i'):
734- ynans = UI_YesNo(_('A profile for %s does not exist.\nDo you want to create one?') %exec_target, 'n')
735+ ynans = aaui.UI_YesNo(_('A profile for %s does not exist.\nDo you want to create one?') % exec_target, 'n')
736 if ynans == 'y':
737 helpers[exec_target] = 'enforce'
738 if to_name:
739@@ -1379,7 +1385,7 @@
740 if not aa[profile].get(exec_target, False):
741 ynans = 'y'
742 if exec_mode & str_to_mode('i'):
743- ynans = UI_YesNo(_('A profile for %s does not exist.\nDo you want to create one?') % exec_target, 'n')
744+ ynans = aaui.UI_YesNo(_('A profile for %s does not exist.\nDo you want to create one?') % exec_target, 'n')
745 if ynans == 'y':
746 hat = exec_target
747 aa[profile][hat]['declared'] = False
748@@ -1488,9 +1494,9 @@
749 for aamode in sorted(log_dict.keys()):
750 # Describe the type of changes
751 if aamode == 'PERMITTING':
752- UI_Info(_('Complain-mode changes:'))
753+ aaui.UI_Info(_('Complain-mode changes:'))
754 elif aamode == 'REJECTING':
755- UI_Info(_('Enforce-mode changes:'))
756+ aaui.UI_Info(_('Enforce-mode changes:'))
757 else:
758 # This is so wrong!
759 fatal_error(_('Invalid mode found: %s') % aamode)
760@@ -1520,7 +1526,7 @@
761 q = hasher()
762
763 if newincludes:
764- options += list(map(lambda inc: '#include <%s>' %inc, sorted(set(newincludes))))
765+ options += list(map(lambda inc: '#include <%s>' % inc, sorted(set(newincludes))))
766
767 if options:
768 options.append('capability %s' % capability)
769@@ -1546,7 +1552,7 @@
770
771 done = False
772 while not done:
773- ans, selected = UI_PromptUser(q)
774+ ans, selected = aaui.UI_PromptUser(q)
775 # Ignore the log entry
776 if ans == 'CMD_IGNORE_ENTRY':
777 done = True
778@@ -1574,27 +1580,27 @@
779 match = re_match_include(selection)
780 if match:
781 deleted = False
782- inc = match #.groups()[0]
783+ inc = match # .groups()[0]
784 deleted = delete_duplicates(aa[profile][hat], inc)
785 aa[profile][hat]['include'][inc] = True
786
787- UI_Info(_('Adding %s to profile.') % selection)
788+ aaui.UI_Info(_('Adding %s to profile.') % selection)
789 if deleted:
790- UI_Info(_('Deleted %s previous matching profile entries.') % deleted)
791+ aaui.UI_Info(_('Deleted %s previous matching profile entries.') % deleted)
792
793 aa[profile][hat]['allow']['capability'][capability]['set'] = True
794 aa[profile][hat]['allow']['capability'][capability]['audit'] = audit_toggle
795
796 changed[profile] = True
797
798- UI_Info(_('Adding capability %s to profile.') % capability)
799+ aaui.UI_Info(_('Adding capability %s to profile.') % capability)
800 done = True
801
802 elif ans == 'CMD_DENY':
803 aa[profile][hat]['deny']['capability'][capability]['set'] = True
804 changed[profile] = True
805
806- UI_Info(_('Denying capability %s to profile.') % capability)
807+ aaui.UI_Info(_('Denying capability %s to profile.') % capability)
808 done = True
809 else:
810 done = False
811@@ -1632,7 +1638,7 @@
812 if cam:
813 deny_audit |= cam
814
815- if deny_mode & AA_MAY_EXEC:
816+ if deny_mode & apparmor.aamode.AA_MAY_EXEC:
817 deny_mode |= apparmor.aamode.ALL_AA_EXEC_TYPE
818
819 # Mask off the denied modes
820@@ -1641,10 +1647,10 @@
821 # If we get an exec request from some kindof event that generates 'PERMITTING X'
822 # check if its already in allow_mode
823 # if not add ix permission
824- if mode & AA_MAY_EXEC:
825+ if mode & apparmor.aamode.AA_MAY_EXEC:
826 # Remove all type access permission
827 mode = mode - apparmor.aamode.ALL_AA_EXEC_TYPE
828- if not allow_mode & AA_MAY_EXEC:
829+ if not allow_mode & apparmor.aamode.AA_MAY_EXEC:
830 mode |= str_to_mode('ix')
831
832 # m is not implied by ix
833@@ -1678,7 +1684,7 @@
834 if aa[profile][hat][incname]:
835 continue
836 if incname.startswith(profile_dir):
837- incname = incname.replace(profile_dir+'/', '', 1)
838+ incname = incname.replace(profile_dir + '/', '', 1)
839
840 include_valid = valid_include('', incname)
841
842@@ -1725,7 +1731,7 @@
843 owner_toggle = cfg['settings']['default_owner_prompt']
844 done = False
845 while not done:
846- q = hasher()
847+ q = hasher()
848 q['headers'] = [_('Profile'), combine_name(profile, hat),
849 _('Path'), path]
850
851@@ -1789,7 +1795,7 @@
852
853 seen_events += 1
854
855- ans, selected = UI_PromptUser(q)
856+ ans, selected = aaui.UI_PromptUser(q)
857
858 if ans == 'CMD_IGNORE_ENTRY':
859 done = True
860@@ -1806,16 +1812,16 @@
861 elif ans == 'CMD_ALLOW':
862 path = options[selected]
863 done = True
864- match = re_match_include(path) #.search('^#include\s+<(.+)>$', path)
865+ match = re_match_include(path) # .search('^#include\s+<(.+)>$', path)
866 if match:
867- inc = match #.groups()[0]
868+ inc = match # .groups()[0]
869 deleted = 0
870 deleted = delete_duplicates(aa[profile][hat], inc)
871- aa[profile][hat]['include'][inc] = True
872- changed[profile] = True
873- UI_Info(_('Adding %s to profile.') % path)
874+ aa[profile][hat]['include'][inc] = True
875+ changed[profile] = True
876+ aaui.UI_Info(_('Adding %s to profile.') % path)
877 if deleted:
878- UI_Info(_('Deleted %s previous matching profile entries.') % deleted)
879+ aaui.UI_Info(_('Deleted %s previous matching profile entries.') % deleted)
880
881 else:
882 if aa[profile][hat]['allow']['path'][path].get('mode', False):
883@@ -1845,7 +1851,7 @@
884
885 tmpmode = set()
886 if audit_toggle == 1:
887- tmpmode = mode- allow_mode
888+ tmpmode = mode - allow_mode
889 elif audit_toggle == 2:
890 tmpmode = mode
891
892@@ -1853,9 +1859,9 @@
893
894 changed[profile] = True
895
896- UI_Info(_('Adding %s %s to profile') % (path, mode_to_str_user(mode)))
897+ aaui.UI_Info(_('Adding %s %s to profile') % (path, mode_to_str_user(mode)))
898 if deleted:
899- UI_Info(_('Deleted %s previous matching profile entries.') % deleted)
900+ aaui.UI_Info(_('Deleted %s previous matching profile entries.') % deleted)
901
902 elif ans == 'CMD_DENY':
903 path = options[selected].strip()
904@@ -1871,11 +1877,11 @@
905 elif ans == 'CMD_NEW':
906 arg = options[selected]
907 if not re_match_include(arg):
908- ans = UI_GetString(_('Enter new path: '), arg)
909+ ans = aaui.UI_GetString(_('Enter new path: '), arg)
910 if ans:
911 if not matchliteral(ans, path):
912- ynprompt = _('The specified path does not match this log entry:\n\n Log Entry: %s\n Entered Path: %s\nDo you really want to use this path?') % (path,ans)
913- key = UI_YesNo(ynprompt, 'n')
914+ ynprompt = _('The specified path does not match this log entry:\n\n Log Entry: %s\n Entered Path: %s\nDo you really want to use this path?') % (path, ans)
915+ key = aaui.UI_YesNo(ynprompt, 'n')
916 if key == 'n':
917 continue
918
919@@ -1919,7 +1925,7 @@
920 newincludes = match_net_includes(aa[profile][hat], family, sock_type)
921 q = hasher()
922 if newincludes:
923- options += list(map(lambda s: '#include <%s>'%s, sorted(set(newincludes))))
924+ options += list(map(lambda s: '#include <%s>' % s, sorted(set(newincludes))))
925 if options:
926 options.append('network %s %s' % (family, sock_type))
927 q['options'] = options
928@@ -1941,7 +1947,7 @@
929
930 done = False
931 while not done:
932- ans, selected = UI_PromptUser(q)
933+ ans, selected = aaui.UI_PromptUser(q)
934 if ans == 'CMD_IGNORE_ENTRY':
935 done = True
936 break
937@@ -1963,18 +1969,18 @@
938 elif ans == 'CMD_ALLOW':
939 selection = options[selected]
940 done = True
941- if re_match_include(selection): #re.search('#include\s+<.+>$', selection):
942- inc = re_match_include(selection) #re.search('#include\s+<(.+)>$', selection).groups()[0]
943- deleted = 0
944+ if re_match_include(selection): # re.search('#include\s+<.+>$', selection):
945+ inc = re_match_include(selection) # re.search('#include\s+<(.+)>$', selection).groups()[0]
946+ deleted = 0
947 deleted = delete_duplicates(aa[profile][hat], inc)
948
949 aa[profile][hat]['include'][inc] = True
950
951 changed[profile] = True
952
953- UI_Info(_('Adding %s to profile') % selection)
954+ aaui.UI_Info(_('Adding %s to profile') % selection)
955 if deleted:
956- UI_Info(_('Deleted %s previous matching profile entries.') % deleted)
957+ aaui.UI_Info(_('Deleted %s previous matching profile entries.') % deleted)
958
959 else:
960 aa[profile][hat]['allow']['netdomain']['audit'][family][sock_type] = audit_toggle
961@@ -1982,13 +1988,13 @@
962
963 changed[profile] = True
964
965- UI_Info(_('Adding network access %s %s to profile.') % (family, sock_type))
966+ aaui.UI_Info(_('Adding network access %s %s to profile.') % (family, sock_type))
967
968 elif ans == 'CMD_DENY':
969 done = True
970 aa[profile][hat]['deny']['netdomain']['rule'][family][sock_type] = True
971 changed[profile] = True
972- UI_Info(_('Denying network access %s %s to profile') % (family, sock_type))
973+ aaui.UI_Info(_('Denying network access %s %s to profile') % (family, sock_type))
974
975 else:
976 done = False
977@@ -1998,13 +2004,13 @@
978 if newpath[-1] == '/':
979 if newpath[-4:] == '/**/' or newpath[-3:] == '/*/':
980 # /foo/**/ and /foo/*/ => /**/
981- newpath = re.sub('/[^/]+/\*{1,2}/$', '/**/', newpath) #re.sub('/[^/]+/\*{1,2}$/', '/\*\*/', newpath)
982+ newpath = re.sub('/[^/]+/\*{1,2}/$', '/**/', newpath) # re.sub('/[^/]+/\*{1,2}$/', '/\*\*/', newpath)
983 elif re.search('/[^/]+\*\*[^/]*/$', newpath):
984 # /foo**/ and /foo**bar/ => /**/
985- newpath = re.sub('/[^/]+\*\*[^/]*/$', '/**/', newpath)
986+ newpath = re.sub('/[^/]+\*\*[^/]*/$', '/**/', newpath)
987 elif re.search('/\*\*[^/]+/$', newpath):
988 # /**bar/ => /**/
989- newpath = re.sub('/\*\*[^/]+/$', '/**/', newpath)
990+ newpath = re.sub('/\*\*[^/]+/$', '/**/', newpath)
991 else:
992 newpath = re.sub('/[^/]+/$', '/*/', newpath)
993 else:
994@@ -2016,7 +2022,7 @@
995 newpath = re.sub('/[^/]*\*\*[^/]+$', '/**', newpath)
996 elif re.search('/[^/]+\*\*$', newpath):
997 # /foo** => /**
998- newpath = re.sub('/[^/]+\*\*$', '/**', newpath)
999+ newpath = re.sub('/[^/]+\*\*$', '/**', newpath)
1000 else:
1001 newpath = re.sub('/[^/]+$', '/*', newpath)
1002 return newpath
1003@@ -2027,19 +2033,19 @@
1004 match = re.search('/\*{1,2}(\.[^/]+)$', newpath)
1005 if match:
1006 # /foo/**.ext and /foo/*.ext => /**.ext
1007- newpath = re.sub('/[^/]+/\*{1,2}\.[^/]+$', '/**'+match.groups()[0], newpath)
1008+ newpath = re.sub('/[^/]+/\*{1,2}\.[^/]+$', '/**' + match.groups()[0], newpath)
1009 elif re.search('/[^/]+\*\*[^/]*\.[^/]+$', newpath):
1010 # /foo**.ext and /foo**bar.ext => /**.ext
1011 match = re.search('/[^/]+\*\*[^/]*(\.[^/]+)$', newpath)
1012- newpath = re.sub('/[^/]+\*\*[^/]*\.[^/]+$', '/**'+match.groups()[0], newpath)
1013+ newpath = re.sub('/[^/]+\*\*[^/]*\.[^/]+$', '/**' + match.groups()[0], newpath)
1014 elif re.search('/\*\*[^/]+\.[^/]+$', newpath):
1015 # /**foo.ext => /**.ext
1016 match = re.search('/\*\*[^/]+(\.[^/]+)$', newpath)
1017- newpath = re.sub('/\*\*[^/]+\.[^/]+$', '/**'+match.groups()[0], newpath)
1018+ newpath = re.sub('/\*\*[^/]+\.[^/]+$', '/**' + match.groups()[0], newpath)
1019 else:
1020 match = re.search('(\.[^/]+)$', newpath)
1021 if match:
1022- newpath = re.sub('/[^/]+(\.[^/]+)$', '/*'+match.groups()[0], newpath)
1023+ newpath = re.sub('/[^/]+(\.[^/]+)$', '/*' + match.groups()[0], newpath)
1024 return newpath
1025
1026 def delete_net_duplicates(netrules, incnetrules):
1027@@ -2081,7 +2087,7 @@
1028 def delete_path_duplicates(profile, incname, allow):
1029 deleted = []
1030 for entry in profile[allow]['path'].keys():
1031- if entry == '#include <%s>'%incname:
1032+ if entry == '#include <%s>' % incname:
1033 continue
1034 cm, am, m = match_include_to_path(incname, allow, entry)
1035 if cm and mode_contains(cm, profile[allow]['path'][entry]['mode']) and mode_contains(am, profile[allow]['path'][entry]['audit']):
1036@@ -2201,10 +2207,10 @@
1037 skip = hasher()
1038 # filelist = hasher()
1039
1040- UI_Info(_('Reading log entries from %s.') %filename)
1041+ aaui.UI_Info(_('Reading log entries from %s.') % filename)
1042
1043 if not passno:
1044- UI_Info(_('Updating AppArmor profiles in %s.') %profile_dir)
1045+ aaui.UI_Info(_('Updating AppArmor profiles in %s.') % profile_dir)
1046 read_profiles()
1047
1048 if not sev_db:
1049@@ -2231,7 +2237,7 @@
1050
1051 ask_the_questions()
1052
1053- if UI_mode == 'yast':
1054+ if aaui.UI_mode == 'yast':
1055 # To-Do
1056 pass
1057
1058@@ -2263,7 +2269,7 @@
1059
1060 if changed_list:
1061
1062- if UI_mode == 'yast':
1063+ if aaui.UI_mode == 'yast':
1064 # To-Do
1065 selected_profiles = []
1066 profile_changes = dict()
1067@@ -2273,8 +2279,7 @@
1068 profile_changes[prof] = get_profile_diff(oldprofile, newprofile)
1069 explanation = _('Select which profile changes you would like to save to the\nlocal profile set.')
1070 title = _('Local profile changes')
1071- SendDataToYast({
1072- 'type': 'dialog-select-profiles',
1073+ SendDataToYast({'type': 'dialog-select-profiles',
1074 'title': title,
1075 'explanation': explanation,
1076 'dialog_select': 'true',
1077@@ -2299,13 +2304,13 @@
1078 q['default'] = 'CMD_VIEW_CHANGES'
1079 q['options'] = changed
1080 q['selected'] = 0
1081- p =None
1082+ p = None
1083 ans = ''
1084 arg = None
1085 while ans != 'CMD_SAVE_CHANGES':
1086 if not changed:
1087 return
1088- ans, arg = UI_PromptUser(q)
1089+ ans, arg = aaui.UI_PromptUser(q)
1090 if ans == 'CMD_SAVE_SELECTED':
1091 profile_name = list(changed.keys())[arg]
1092 write_profile_ui_feedback(profile_name)
1093@@ -2350,7 +2355,7 @@
1094
1095 difftemp = tempfile.NamedTemporaryFile('w', delete=False)
1096
1097- subprocess.call('diff -u -p %s %s > %s' %(oldtemp.name, newtemp.name, difftemp.name), shell=True)
1098+ subprocess.call('diff -u -p %s %s > %s' % (oldtemp.name, newtemp.name, difftemp.name), shell=True)
1099
1100 oldtemp.close()
1101 newtemp.close()
1102@@ -2369,19 +2374,19 @@
1103 return ''.join(diff)
1104
1105 def display_changes(oldprofile, newprofile):
1106- if UI_mode == 'yast':
1107- UI_LongMessage(_('Profile Changes'), get_profile_diff(oldprofile, newprofile))
1108+ if aaui.UI_mode == 'yast':
1109+ aaui.UI_LongMessage(_('Profile Changes'), get_profile_diff(oldprofile, newprofile))
1110 else:
1111 difftemp = generate_diff(oldprofile, newprofile)
1112- subprocess.call('less %s' %difftemp.name, shell=True)
1113+ subprocess.call('less %s' % difftemp.name, shell=True)
1114 difftemp.delete = True
1115 difftemp.close()
1116
1117 def display_changes_with_comments(oldprofile, newprofile):
1118 """Compare the new profile with the existing profile inclusive of all the comments"""
1119 if not os.path.exists(oldprofile):
1120- raise AppArmorException(_("Can't find existing profile %s to compare changes.") %oldprofile)
1121- if UI_mode == 'yast':
1122+ raise AppArmorException(_("Can't find existing profile %s to compare changes.") % oldprofile)
1123+ if aaui.UI_mode == 'yast':
1124 #To-Do
1125 pass
1126 else:
1127@@ -2391,10 +2396,10 @@
1128
1129 difftemp = tempfile.NamedTemporaryFile('w')
1130
1131- subprocess.call('diff -u -p %s %s > %s' %(oldprofile, newtemp.name, difftemp.name), shell=True)
1132+ subprocess.call('diff -u -p %s %s > %s' % (oldprofile, newtemp.name, difftemp.name), shell=True)
1133
1134 newtemp.close()
1135- subprocess.call('less %s' %difftemp.name, shell=True)
1136+ subprocess.call('less %s' % difftemp.name, shell=True)
1137 difftemp.close()
1138
1139 def set_process(pid, profile):
1140@@ -2497,8 +2502,8 @@
1141 def is_skippable_file(path):
1142 """Returns True if filename matches something to be skipped"""
1143 if (re.search('(^|/)\.[^/]*$', path) or re.search('\.rpm(save|new)$', path)
1144- or re.search('\.dpkg-(old|new)$', path) or re.search('\.swp$', path)
1145- or path[-1] == '~' or path == 'README'):
1146+ or re.search('\.dpkg-(old|new)$', path) or re.search('\.swp$', path)
1147+ or path[-1] == '~' or path == 'README'):
1148 return True
1149
1150 def is_skippable_dir(path):
1151@@ -2517,7 +2522,7 @@
1152 def read_profiles():
1153 try:
1154 os.listdir(profile_dir)
1155- except :
1156+ except:
1157 fatal_error(_("Can't read AppArmor profiles in %s") % profile_dir)
1158
1159 for file in os.listdir(profile_dir):
1160@@ -2532,7 +2537,7 @@
1161 return None
1162 try:
1163 os.listdir(profile_dir)
1164- except :
1165+ except:
1166 fatal_error(_("Can't read AppArmor profiles in %s") % extra_profile_dir)
1167
1168 for file in os.listdir(profile_dir):
1169@@ -2548,7 +2553,7 @@
1170 with open_file_read(file) as f_in:
1171 data = f_in.readlines()
1172 except IOError:
1173- debug_logger.debug("read_profile: can't read %s - skipping" %file)
1174+ debug_logger.debug("read_profile: can't read %s - skipping" % file)
1175 return None
1176
1177 profile_data = parse_profile_data(data, file, 0)
1178@@ -2609,13 +2614,13 @@
1179 if profile:
1180 #print(profile, hat)
1181 if profile != hat or not matches[3]:
1182- raise AppArmorException(_('%s profile in %s contains syntax errors in line: %s.') % (profile, file, lineno+1))
1183+ raise AppArmorException(_('%s profile in %s contains syntax errors in line: %s.') % (profile, file, lineno + 1))
1184 # Keep track of the start of a profile
1185 if profile and profile == hat and matches[3]:
1186 # local profile
1187 hat = matches[3]
1188 in_contained_hat = True
1189- profile_data[profile][hat]['profile'] = True
1190+ profile_data[profile][hat]['profile'] = True
1191 else:
1192 if matches[1]:
1193 profile = matches[1]
1194@@ -2661,7 +2666,7 @@
1195 elif RE_PROFILE_END.search(line):
1196 # If profile ends and we're not in one
1197 if not profile:
1198- raise AppArmorException(_('Syntax Error: Unexpected End of Profile reached in file: %s line: %s') % (file, lineno+1))
1199+ raise AppArmorException(_('Syntax Error: Unexpected End of Profile reached in file: %s line: %s') % (file, lineno + 1))
1200
1201 if in_contained_hat:
1202 hat = profile
1203@@ -2676,7 +2681,7 @@
1204 matches = RE_PROFILE_CAP.search(line).groups()
1205
1206 if not profile:
1207- raise AppArmorException(_('Syntax Error: Unexpected capability entry found in file: %s line: %s') % (file, lineno+1))
1208+ raise AppArmorException(_('Syntax Error: Unexpected capability entry found in file: %s line: %s') % (file, lineno + 1))
1209
1210 audit = False
1211 if matches[0]:
1212@@ -2695,7 +2700,7 @@
1213 matches = RE_PROFILE_LINK.search(line).groups()
1214
1215 if not profile:
1216- raise AppArmorException(_('Syntax Error: Unexpected link entry found in file: %s line: %s') % (file, lineno+1))
1217+ raise AppArmorException(_('Syntax Error: Unexpected link entry found in file: %s line: %s') % (file, lineno + 1))
1218
1219 audit = False
1220 if matches[0]:
1221@@ -2709,13 +2714,13 @@
1222 link = strip_quotes(matches[6])
1223 value = strip_quotes(matches[7])
1224 profile_data[profile][hat][allow]['link'][link]['to'] = value
1225- profile_data[profile][hat][allow]['link'][link]['mode'] = profile_data[profile][hat][allow]['link'][link].get('mode', set()) | AA_MAY_LINK
1226+ profile_data[profile][hat][allow]['link'][link]['mode'] = profile_data[profile][hat][allow]['link'][link].get('mode', set()) | apparmor.aamode.AA_MAY_LINK
1227
1228 if subset:
1229- profile_data[profile][hat][allow]['link'][link]['mode'] |= AA_LINK_SUBSET
1230+ profile_data[profile][hat][allow]['link'][link]['mode'] |= apparmor.aamode.AA_LINK_SUBSET
1231
1232 if audit:
1233- profile_data[profile][hat][allow]['link'][link]['audit'] = profile_data[profile][hat][allow]['link'][link].get('audit', set()) | AA_LINK_SUBSET
1234+ profile_data[profile][hat][allow]['link'][link]['audit'] = profile_data[profile][hat][allow]['link'][link].get('audit', set()) | apparmor.aamode.AA_LINK_SUBSET
1235 else:
1236 profile_data[profile][hat][allow]['link'][link]['audit'] = set()
1237
1238@@ -2723,7 +2728,7 @@
1239 matches = RE_PROFILE_CHANGE_PROFILE.search(line).groups()
1240
1241 if not profile:
1242- raise AppArmorException(_('Syntax Error: Unexpected change profile entry found in file: %s line: %s') % (file, lineno+1))
1243+ raise AppArmorException(_('Syntax Error: Unexpected change profile entry found in file: %s line: %s') % (file, lineno + 1))
1244
1245 cp = strip_quotes(matches[0])
1246 profile_data[profile][hat]['changes_profile'][cp] = True
1247@@ -2745,7 +2750,7 @@
1248 matches = RE_PROFILE_RLIMIT.search(line).groups()
1249
1250 if not profile:
1251- raise AppArmorException(_('Syntax Error: Unexpected rlimit entry found in file: %s line: %s') % (file, lineno+1))
1252+ raise AppArmorException(_('Syntax Error: Unexpected rlimit entry found in file: %s line: %s') % (file, lineno + 1))
1253
1254 from_name = matches[0]
1255 to_name = matches[2]
1256@@ -2756,7 +2761,7 @@
1257 matches = RE_PROFILE_BOOLEAN.search(line)
1258
1259 if not profile:
1260- raise AppArmorException(_('Syntax Error: Unexpected boolean definition found in file: %s line: %s') % (file, lineno+1))
1261+ raise AppArmorException(_('Syntax Error: Unexpected boolean definition found in file: %s line: %s') % (file, lineno + 1))
1262
1263 bool_var = matches[0]
1264 value = matches[1]
1265@@ -2796,7 +2801,7 @@
1266 matches = RE_PROFILE_PATH_ENTRY.search(line).groups()
1267
1268 if not profile:
1269- raise AppArmorException(_('Syntax Error: Unexpected path entry found in file: %s line: %s') % (file, lineno+1))
1270+ raise AppArmorException(_('Syntax Error: Unexpected path entry found in file: %s line: %s') % (file, lineno + 1))
1271
1272 audit = False
1273 if matches[0]:
1274@@ -2820,10 +2825,10 @@
1275 try:
1276 re.compile(p_re)
1277 except:
1278- raise AppArmorException(_('Syntax Error: Invalid Regex %s in file: %s line: %s') % (path, file, lineno+1))
1279+ raise AppArmorException(_('Syntax Error: Invalid Regex %s in file: %s line: %s') % (path, file, lineno + 1))
1280
1281 if not validate_profile_mode(mode, allow, nt_name):
1282- raise AppArmorException(_('Invalid mode %s in file: %s line: %s') % (mode, file, lineno+1))
1283+ raise AppArmorException(_('Invalid mode %s in file: %s line: %s') % (mode, file, lineno + 1))
1284
1285 tmpmode = set()
1286 if user:
1287@@ -2847,7 +2852,6 @@
1288 if include_name.startswith('local/'):
1289 profile_data[profile][hat]['localinclude'][include_name] = True
1290
1291-
1292 if profile:
1293 profile_data[profile][hat]['include'][include_name] = True
1294 else:
1295@@ -2862,7 +2866,7 @@
1296 continue
1297 if os.path.isfile(profile_dir + '/' + include_name + '/' + path):
1298 file_name = include_name + '/' + path
1299- file_name = file_name.replace(profile_dir+'/', '')
1300+ file_name = file_name.replace(profile_dir + '/', '')
1301 if not include.get(file_name, False):
1302 load_include(file_name)
1303 else:
1304@@ -2873,7 +2877,7 @@
1305 matches = RE_PROFILE_NETWORK.search(line).groups()
1306
1307 if not profile:
1308- raise AppArmorException(_('Syntax Error: Unexpected network entry found in file: %s line: %s') % (file, lineno+1))
1309+ raise AppArmorException(_('Syntax Error: Unexpected network entry found in file: %s line: %s') % (file, lineno + 1))
1310
1311 audit = False
1312 if matches[0]:
1313@@ -2889,7 +2893,7 @@
1314 ##Simply ignore any type subrules if family has True (seperately for allow and deny)
1315 ##This will lead to those type specific rules being lost when written
1316 #if type(profile_data[profile][hat][allow]['netdomain']['rule'].get(fam, False)) == dict:
1317- profile_data[profile][hat][allow]['netdomain']['rule'][fam][typ] = 1
1318+ profile_data[profile][hat][allow]['netdomain']['rule'][fam][typ] = 1
1319 profile_data[profile][hat][allow]['netdomain']['audit'][fam][typ] = audit
1320 elif RE_NETWORK_FAMILY.search(network):
1321 fam = RE_NETWORK_FAMILY.search(network).groups()[0]
1322@@ -2897,13 +2901,13 @@
1323 profile_data[profile][hat][allow]['netdomain']['audit'][fam] = audit
1324 else:
1325 profile_data[profile][hat][allow]['netdomain']['rule']['all'] = True
1326- profile_data[profile][hat][allow]['netdomain']['audit']['all'] = audit # True
1327+ profile_data[profile][hat][allow]['netdomain']['audit']['all'] = audit # True
1328
1329 elif RE_PROFILE_CHANGE_HAT.search(line):
1330 matches = RE_PROFILE_CHANGE_HAT.search(line).groups()
1331
1332 if not profile:
1333- raise AppArmorException(_('Syntax Error: Unexpected change hat declaration found in file: %s line: %s') % (file, lineno+1))
1334+ raise AppArmorException(_('Syntax Error: Unexpected change hat declaration found in file: %s line: %s') % (file, lineno + 1))
1335
1336 hat = matches[0]
1337 hat = strip_quotes(hat)
1338@@ -2915,7 +2919,7 @@
1339 # An embedded hat syntax definition starts
1340 matches = RE_PROFILE_HAT_DEF.search(line).groups()
1341 if not profile:
1342- raise AppArmorException(_('Syntax Error: Unexpected hat definition found in file: %s line: %s') % (file, lineno+1))
1343+ raise AppArmorException(_('Syntax Error: Unexpected hat definition found in file: %s line: %s') % (file, lineno + 1))
1344
1345 in_contained_hat = True
1346 hat = matches[0]
1347@@ -2931,7 +2935,7 @@
1348 profile_data[profile][hat]['initial_comment'] = initial_comment
1349 initial_comment = ''
1350 if filelist[file]['profiles'][profile].get(hat, False):
1351- raise AppArmorException(_('Error: Multiple definitions for hat %s in profile %s.') %(hat, profile))
1352+ raise AppArmorException(_('Error: Multiple definitions for hat %s in profile %s.') % (hat, profile))
1353 filelist[file]['profiles'][profile][hat] = True
1354
1355 elif line[0] == '#':
1356@@ -2951,7 +2955,7 @@
1357 initial_comment = ' '.join(line) + '\n'
1358
1359 else:
1360- raise AppArmorException(_('Syntax Error: Unknown line found in file: %s line: %s') % (file, lineno+1))
1361+ raise AppArmorException(_('Syntax Error: Unknown line found in file: %s line: %s') % (file, lineno + 1))
1362
1363 # Below is not required I'd say
1364 if not do_include:
1365@@ -2995,18 +2999,18 @@
1366 var[list_var] = set(vlist)
1367 else:
1368 #print('Ignored: New definition for variable for:',list_var,'=', value, 'operation was:',var_operation,'old value=', var[list_var])
1369- raise AppArmorException(_('An existing variable redefined: %s') %list_var)
1370+ raise AppArmorException(_('An existing variable redefined: %s') % list_var)
1371 elif var_operation == '+=':
1372 if var.get(list_var, False):
1373 var[list_var] = set(var[list_var] + vlist)
1374 else:
1375- raise AppArmorException(_('Values added to a non-existing variable: %s') %list_var)
1376+ raise AppArmorException(_('Values added to a non-existing variable: %s') % list_var)
1377 else:
1378- raise AppArmorException(_('Unknown variable operation: %s') %var_operation)
1379+ raise AppArmorException(_('Unknown variable operation: %s') % var_operation)
1380
1381
1382 def strip_quotes(data):
1383- if data[0]+data[-1] == '""':
1384+ if data[0] + data[-1] == '""':
1385 return data[1:-1]
1386 else:
1387 return data
1388@@ -3029,7 +3033,7 @@
1389 data = []
1390 name = quote_if_needed(name)
1391
1392- if (not embedded_hat and re.search('^[^/]|^"[^/]', name)) or (embedded_hat and re.search('^[^^]' ,name)):
1393+ if (not embedded_hat and re.search('^[^/]|^"[^/]', name)) or (embedded_hat and re.search('^[^^]', name)):
1394 name = 'profile %s' % name
1395
1396 if write_flags and prof_data['flags']:
1397@@ -3047,7 +3051,7 @@
1398 if ref.get(name, False):
1399 for key in sorted(ref[name].keys()):
1400 qkey = quote_if_needed(key)
1401- data.append('%s%s%s%s%s' %(pre, allow, prefix, qkey, tail))
1402+ data.append('%s%s%s%s%s' % (pre, allow, prefix, qkey, tail))
1403 if ref[name].keys():
1404 data.append('')
1405
1406@@ -3077,8 +3081,8 @@
1407
1408 if ref.get(name, False):
1409 for key in sorted(ref[name].keys()):
1410- value = fn(ref[name][key])#eval('%s(%s)' % (fn, ref[name][key]))
1411- data.append('%s%s%s%s%s%s' %(pre, allow, prefix, key, sep, value))
1412+ value = fn(ref[name][key]) # eval('%s(%s)' % (fn, ref[name][key]))
1413+ data.append('%s%s%s%s%s%s' % (pre, allow, prefix, key, sep, value))
1414 if ref[name].keys():
1415 data.append('')
1416
1417@@ -3116,7 +3120,7 @@
1418 if prof_data[allow]['capability'][cap].get('audit', False):
1419 audit = 'audit '
1420 if prof_data[allow]['capability'][cap].get('set', False):
1421- data.append('%s%s%scapability %s,' %(pre, audit, allowstr, cap))
1422+ data.append('%s%s%scapability %s,' % (pre, audit, allowstr, cap))
1423 data.append('')
1424
1425 return data
1426@@ -3136,10 +3140,10 @@
1427 if prof_data[allow]['netdomain'].get('rule', False) == 'all':
1428 if prof_data[allow]['netdomain']['audit'].get('all', False):
1429 audit = 'audit '
1430- data.append('%s%snetwork,' %(pre, audit))
1431+ data.append('%s%snetwork,' % (pre, audit))
1432 else:
1433 for fam in sorted(prof_data[allow]['netdomain']['rule'].keys()):
1434- if prof_data[allow]['netdomain']['rule'][fam] == True:
1435+ if prof_data[allow]['netdomain']['rule'][fam] is True:
1436 if prof_data[allow]['netdomain']['audit'][fam]:
1437 audit = 'audit'
1438 data.append('%s%s%snetwork %s' % (pre, audit, allowstr, fam))
1439@@ -3147,7 +3151,7 @@
1440 for typ in sorted(prof_data[allow]['netdomain']['rule'][fam].keys()):
1441 if prof_data[allow]['netdomain']['audit'][fam].get(typ, False):
1442 audit = 'audit'
1443- data.append('%s%s%snetwork %s %s,' % (pre, audit, allowstr,fam, typ))
1444+ data.append('%s%s%snetwork %s %s,' % (pre, audit, allowstr, fam, typ))
1445 if prof_data[allow].get('netdomain', False):
1446 data.append('')
1447
1448@@ -3167,14 +3171,14 @@
1449 for path in sorted(prof_data[allow]['link'].keys()):
1450 to_name = prof_data[allow]['link'][path]['to']
1451 subset = ''
1452- if prof_data[allow]['link'][path]['mode'] & AA_LINK_SUBSET:
1453+ if prof_data[allow]['link'][path]['mode'] & apparmor.aamode.AA_LINK_SUBSET:
1454 subset = 'subset'
1455 audit = ''
1456 if prof_data[allow]['link'][path].get('audit', False):
1457 audit = 'audit '
1458 path = quote_if_needed(path)
1459 to_name = quote_if_needed(to_name)
1460- data.append('%s%s%slink %s%s -> %s,' %(pre, audit, allowstr, subset, path, to_name))
1461+ data.append('%s%s%slink %s%s -> %s,' % (pre, audit, allowstr, subset, path, to_name))
1462 data.append('')
1463
1464 return data
1465@@ -3226,13 +3230,13 @@
1466 if tmpmode & tmpaudit:
1467 modestr = mode_to_str(tmpmode & tmpaudit)
1468 path = quote_if_needed(path)
1469- data.append('%saudit %s%s%s %s%s,' %(pre, allowstr, ownerstr, path, modestr, tail))
1470+ data.append('%saudit %s%s%s %s%s,' % (pre, allowstr, ownerstr, path, modestr, tail))
1471 tmpmode = tmpmode - tmpaudit
1472
1473 if tmpmode:
1474 modestr = mode_to_str(tmpmode)
1475 path = quote_if_needed(path)
1476- data.append('%s%s%s%s %s%s,' %(pre, allowstr, ownerstr, path, modestr, tail))
1477+ data.append('%s%s%s%s %s%s,' % (pre, allowstr, ownerstr, path, modestr, tail))
1478
1479 data.append('')
1480 return data
1481@@ -3268,13 +3272,13 @@
1482 name = nhat
1483 inhat = True
1484 data += write_header(profile_data[name], depth, wname, False, write_flags)
1485- data += write_rules(profile_data[name], depth+1)
1486+ data += write_rules(profile_data[name], depth + 1)
1487
1488- pre2 = ' ' * (depth+1)
1489+ pre2 = ' ' * (depth + 1)
1490 # External hat declarations
1491 for hat in list(filter(lambda x: x != name, sorted(profile_data.keys()))):
1492 if profile_data[hat].get('declared', False):
1493- data.append('%s^%s,' %(pre2, hat))
1494+ data.append('%s^%s,' % (pre2, hat))
1495
1496 if not inhat:
1497 # Embedded hats
1498@@ -3282,21 +3286,21 @@
1499 if not profile_data[hat]['external'] and not profile_data[hat]['declared']:
1500 data.append('')
1501 if profile_data[hat]['profile']:
1502- data += list(map(str, write_header(profile_data[hat], depth+1, hat, True, write_flags)))
1503+ data += list(map(str, write_header(profile_data[hat], depth + 1, hat, True, write_flags)))
1504 else:
1505- data += list(map(str, write_header(profile_data[hat], depth+1, '^'+hat, True, write_flags)))
1506-
1507- data += list(map(str, write_rules(profile_data[hat], depth+2)))
1508-
1509- data.append('%s}' %pre2)
1510-
1511- data.append('%s}' %pre)
1512+ data += list(map(str, write_header(profile_data[hat], depth + 1, '^' + hat, True, write_flags)))
1513+
1514+ data += list(map(str, write_rules(profile_data[hat], depth + 2)))
1515+
1516+ data.append('%s}' % pre2)
1517+
1518+ data.append('%s}' % pre)
1519
1520 # External hats
1521 for hat in list(filter(lambda x: x != name, sorted(profile_data.keys()))):
1522 if name == nhat and profile_data[hat].get('external', False):
1523 data.append('')
1524- data += list(map(lambda x: ' %s' %x, write_piece(profile_data, depth-1, name, nhat, write_flags)))
1525+ data += list(map(lambda x: ' %s' % x, write_piece(profile_data, depth - 1, name, nhat, write_flags)))
1526 data.append(' }')
1527
1528 return data
1529@@ -3305,21 +3309,23 @@
1530 string = ''
1531 include_metadata = False
1532 include_flags = True
1533- data= []
1534+ data = []
1535
1536- if options:# and type(options) == dict:
1537+ if options: # and type(options) == dict:
1538 if options.get('METADATA', False):
1539 include_metadata = True
1540 if options.get('NO_FLAGS', False):
1541 include_flags = False
1542
1543 if include_metadata:
1544- string = '# Last Modified: %s\n' %time.asctime()
1545+ string = '# Last Modified: %s\n' % time.asctime()
1546
1547- if (profile_data[name].get('repo', False) and profile_data[name]['repo']['url']
1548- and profile_data[name]['repo']['user'] and profile_data[name]['repo']['id']):
1549+ if (profile_data[name].get('repo', False) and
1550+ profile_data[name]['repo']['url'] and
1551+ profile_data[name]['repo']['user'] and
1552+ profile_data[name]['repo']['id']):
1553 repo = profile_data[name]['repo']
1554- string += '# REPOSITORY: %s %s %s\n' %(repo['url'], repo['user'], repo['id'])
1555+ string += '# REPOSITORY: %s %s %s\n' % (repo['url'], repo['user'], repo['id'])
1556 elif profile_data[name]['repo']['neversubmit']:
1557 string += '# REPOSITORY: NEVERSUBMIT\n'
1558
1559@@ -3351,7 +3357,7 @@
1560
1561 string += '\n'.join(data)
1562
1563- return string+'\n'
1564+ return string + '\n'
1565
1566 def serialize_profile_from_old_profile(profile_data, name, options):
1567 data = []
1568@@ -3363,28 +3369,29 @@
1569 write_filelist = deepcopy(filelist[prof_filename])
1570 write_prof_data = deepcopy(profile_data)
1571
1572- if options:# and type(options) == dict:
1573+ if options: # and type(options) == dict:
1574 if options.get('METADATA', False):
1575 include_metadata = True
1576 if options.get('NO_FLAGS', False):
1577 include_flags = False
1578
1579 if include_metadata:
1580- string = '# Last Modified: %s\n' %time.asctime()
1581+ string = '# Last Modified: %s\n' % time.asctime()
1582
1583- if (profile_data[name].get('repo', False) and profile_data[name]['repo']['url']
1584- and profile_data[name]['repo']['user'] and profile_data[name]['repo']['id']):
1585+ if (profile_data[name].get('repo', False) and
1586+ profile_data[name]['repo']['url'] and
1587+ profile_data[name]['repo']['user'] and
1588+ profile_data[name]['repo']['id']):
1589 repo = profile_data[name]['repo']
1590- string += '# REPOSITORY: %s %s %s\n' %(repo['url'], repo['user'], repo['id'])
1591+ string += '# REPOSITORY: %s %s %s\n' % (repo['url'], repo['user'], repo['id'])
1592 elif profile_data[name]['repo']['neversubmit']:
1593 string += '# REPOSITORY: NEVERSUBMIT\n'
1594
1595-
1596 if not os.path.isfile(prof_filename):
1597 raise AppArmorException(_("Can't find existing profile to modify"))
1598-
1599+
1600 profiles_list = filelist[prof_filename].keys()
1601-
1602+
1603 with open_file_read(prof_filename) as f_in:
1604 profile = None
1605 hat = None
1606@@ -3399,8 +3406,7 @@
1607 'change_profile': write_change_profile,
1608 }
1609 prof_correct = True
1610- segments = {
1611- 'alias': False,
1612+ segments = {'alias': False,
1613 'lvar': False,
1614 'include': False,
1615 'rlimit': False,
1616@@ -3410,7 +3416,7 @@
1617 'path': False,
1618 'change_profile': False,
1619 'include_local_started': False,
1620- }
1621+ }
1622 #data.append('reading prof')
1623 for line in f_in:
1624 correct = True
1625@@ -3446,7 +3452,7 @@
1626 if not write_prof_data[hat]['name'] == profile:
1627 correct = False
1628
1629- if not write_filelist['profiles'][profile][hat] == True:
1630+ if not write_filelist['profiles'][profile][hat] is True:
1631 correct = False
1632
1633 if not write_prof_data[hat]['flags'] == flags:
1634@@ -3462,7 +3468,7 @@
1635 else:
1636 if write_prof_data[hat]['name'] == profile:
1637 depth = len(line) - len(line.lstrip())
1638- data += write_header(write_prof_data[name], int(depth/2), name, False, include_flags)
1639+ data += write_header(write_prof_data[name], int(depth / 2), name, False, include_flags)
1640
1641 elif RE_PROFILE_END.search(line):
1642 # DUMP REMAINDER OF PROFILE
1643@@ -3471,11 +3477,12 @@
1644 if True in segments.values():
1645 for segs in list(filter(lambda x: segments[x], segments.keys())):
1646
1647- data += write_methods[segs](write_prof_data[name], int(depth/2))
1648+ data += write_methods[segs](write_prof_data[name], int(depth / 2))
1649 segments[segs] = False
1650- if write_prof_data[name]['allow'].get(segs, False): write_prof_data[name]['allow'].pop(segs)
1651- if write_prof_data[name]['deny'].get(segs, False): write_prof_data[name]['deny'].pop(segs)
1652-
1653+ if write_prof_data[name]['allow'].get(segs, False):
1654+ write_prof_data[name]['allow'].pop(segs)
1655+ if write_prof_data[name]['deny'].get(segs, False):
1656+ write_prof_data[name]['deny'].pop(segs)
1657
1658 data += write_alias(write_prof_data[name], depth)
1659 data += write_list_vars(write_prof_data[name], depth)
1660@@ -3494,25 +3501,25 @@
1661
1662 if not in_contained_hat:
1663 # Embedded hats
1664- depth = int((len(line) - len(line.lstrip()))/2)
1665- pre2 = ' ' * (depth+1)
1666+ depth = int((len(line) - len(line.lstrip())) / 2)
1667+ pre2 = ' ' * (depth + 1)
1668 for hat in list(filter(lambda x: x != name, sorted(profile_data.keys()))):
1669 if not profile_data[hat]['external'] and not profile_data[hat]['declared']:
1670 data.append('')
1671 if profile_data[hat]['profile']:
1672- data += list(map(str, write_header(profile_data[hat], depth+1, hat, True, include_flags)))
1673+ data += list(map(str, write_header(profile_data[hat], depth + 1, hat, True, include_flags)))
1674 else:
1675- data += list(map(str, write_header(profile_data[hat], depth+1, '^'+hat, True, include_flags)))
1676-
1677- data += list(map(str, write_rules(profile_data[hat], depth+2)))
1678-
1679- data.append('%s}' %pre2)
1680+ data += list(map(str, write_header(profile_data[hat], depth + 1, '^' + hat, True, include_flags)))
1681+
1682+ data += list(map(str, write_rules(profile_data[hat], depth + 2)))
1683+
1684+ data.append('%s}' % pre2)
1685
1686 # External hats
1687 for hat in list(filter(lambda x: x != name, sorted(profile_data.keys()))):
1688 if profile_data[hat].get('external', False):
1689 data.append('')
1690- data += list(map(lambda x: ' %s' %x, write_piece(profile_data, depth-1, name, name, include_flags)))
1691+ data += list(map(lambda x: ' %s' % x, write_piece(profile_data, depth - 1, name, name, include_flags)))
1692 data.append(' }')
1693
1694 if in_contained_hat:
1695@@ -3522,7 +3529,6 @@
1696 else:
1697 profile = None
1698
1699-
1700 elif RE_PROFILE_CAP.search(line):
1701 matches = RE_PROFILE_CAP.search(line).groups()
1702 audit = False
1703@@ -3544,10 +3550,12 @@
1704 if not segments['capability'] and True in segments.values():
1705 for segs in list(filter(lambda x: segments[x], segments.keys())):
1706 depth = len(line) - len(line.lstrip())
1707- data += write_methods[segs](write_prof_data[name], int(depth/2))
1708+ data += write_methods[segs](write_prof_data[name], int(depth / 2))
1709 segments[segs] = False
1710- if write_prof_data[name]['allow'].get(segs, False): write_prof_data[name]['allow'].pop(segs)
1711- if write_prof_data[name]['deny'].get(segs, False): write_prof_data[name]['deny'].pop(segs)
1712+ if write_prof_data[name]['allow'].get(segs, False):
1713+ write_prof_data[name]['allow'].pop(segs)
1714+ if write_prof_data[name]['deny'].get(segs, False):
1715+ write_prof_data[name]['deny'].pop(segs)
1716 segments['capability'] = True
1717 write_prof_data[hat][allow]['capability'].pop(capability)
1718 data.append(line)
1719@@ -3572,21 +3580,23 @@
1720 value = strip_quotes(matches[7])
1721 if not write_prof_data[hat][allow]['link'][link]['to'] == value:
1722 correct = False
1723- if not write_prof_data[hat][allow]['link'][link]['mode'] & AA_MAY_LINK:
1724- correct = False
1725- if subset and not write_prof_data[hat][allow]['link'][link]['mode'] & AA_LINK_SUBSET:
1726- correct = False
1727- if audit and not write_prof_data[hat][allow]['link'][link]['audit'] & AA_LINK_SUBSET:
1728+ if not write_prof_data[hat][allow]['link'][link]['mode'] & apparmor.aamode.AA_MAY_LINK:
1729+ correct = False
1730+ if subset and not write_prof_data[hat][allow]['link'][link]['mode'] & apparmor.aamode.AA_LINK_SUBSET:
1731+ correct = False
1732+ if audit and not write_prof_data[hat][allow]['link'][link]['audit'] & apparmor.aamode.AA_LINK_SUBSET:
1733 correct = False
1734
1735 if correct:
1736 if not segments['link'] and True in segments.values():
1737 for segs in list(filter(lambda x: segments[x], segments.keys())):
1738 depth = len(line) - len(line.lstrip())
1739- data += write_methods[segs](write_prof_data[name], int(depth/2))
1740+ data += write_methods[segs](write_prof_data[name], int(depth / 2))
1741 segments[segs] = False
1742- if write_prof_data[name]['allow'].get(segs, False): write_prof_data[name]['allow'].pop(segs)
1743- if write_prof_data[name]['deny'].get(segs, False): write_prof_data[name]['deny'].pop(segs)
1744+ if write_prof_data[name]['allow'].get(segs, False):
1745+ write_prof_data[name]['allow'].pop(segs)
1746+ if write_prof_data[name]['deny'].get(segs, False):
1747+ write_prof_data[name]['deny'].pop(segs)
1748 segments['link'] = True
1749 write_prof_data[hat][allow]['link'].pop(link)
1750 data.append(line)
1751@@ -3598,17 +3608,19 @@
1752 matches = RE_PROFILE_CHANGE_PROFILE.search(line).groups()
1753 cp = strip_quotes(matches[0])
1754
1755- if not write_prof_data[hat]['changes_profile'][cp] == True:
1756+ if not write_prof_data[hat]['changes_profile'][cp] is True:
1757 correct = False
1758
1759 if correct:
1760 if not segments['change_profile'] and True in segments.values():
1761 for segs in list(filter(lambda x: segments[x], segments.keys())):
1762 depth = len(line) - len(line.lstrip())
1763- data += write_methods[segs](write_prof_data[name], int(depth/2))
1764+ data += write_methods[segs](write_prof_data[name], int(depth / 2))
1765 segments[segs] = False
1766- if write_prof_data[name]['allow'].get(segs, False): write_prof_data[name]['allow'].pop(segs)
1767- if write_prof_data[name]['deny'].get(segs, False): write_prof_data[name]['deny'].pop(segs)
1768+ if write_prof_data[name]['allow'].get(segs, False):
1769+ write_prof_data[name]['allow'].pop(segs)
1770+ if write_prof_data[name]['deny'].get(segs, False):
1771+ write_prof_data[name]['deny'].pop(segs)
1772 segments['change_profile'] = True
1773 write_prof_data[hat]['change_profile'].pop(cp)
1774 data.append(line)
1775@@ -3633,10 +3645,12 @@
1776 if not segments['alias'] and True in segments.values():
1777 for segs in list(filter(lambda x: segments[x], segments.keys())):
1778 depth = len(line) - len(line.lstrip())
1779- data += write_methods[segs](write_prof_data[name], int(depth/2))
1780+ data += write_methods[segs](write_prof_data[name], int(depth / 2))
1781 segments[segs] = False
1782- if write_prof_data[name]['allow'].get(segs, False): write_prof_data[name]['allow'].pop(segs)
1783- if write_prof_data[name]['deny'].get(segs, False): write_prof_data[name]['deny'].pop(segs)
1784+ if write_prof_data[name]['allow'].get(segs, False):
1785+ write_prof_data[name]['allow'].pop(segs)
1786+ if write_prof_data[name]['deny'].get(segs, False):
1787+ write_prof_data[name]['deny'].pop(segs)
1788 segments['alias'] = True
1789 if profile:
1790 write_prof_data[hat]['alias'].pop(from_name)
1791@@ -3660,10 +3674,12 @@
1792 if not segments['rlimit'] and True in segments.values():
1793 for segs in list(filter(lambda x: segments[x], segments.keys())):
1794 depth = len(line) - len(line.lstrip())
1795- data += write_methods[segs](write_prof_data[name], int(depth/2))
1796+ data += write_methods[segs](write_prof_data[name], int(depth / 2))
1797 segments[segs] = False
1798- if write_prof_data[name]['allow'].get(segs, False): write_prof_data[name]['allow'].pop(segs)
1799- if write_prof_data[name]['deny'].get(segs, False): write_prof_data[name]['deny'].pop(segs)
1800+ if write_prof_data[name]['allow'].get(segs, False):
1801+ write_prof_data[name]['allow'].pop(segs)
1802+ if write_prof_data[name]['deny'].get(segs, False):
1803+ write_prof_data[name]['deny'].pop(segs)
1804 segments['rlimit'] = True
1805 write_prof_data[hat]['rlimit'].pop(from_name)
1806 data.append(line)
1807@@ -3683,10 +3699,12 @@
1808 if not segments['lvar'] and True in segments.values():
1809 for segs in list(filter(lambda x: segments[x], segments.keys())):
1810 depth = len(line) - len(line.lstrip())
1811- data += write_methods[segs](write_prof_data[name], int(depth/2))
1812+ data += write_methods[segs](write_prof_data[name], int(depth / 2))
1813 segments[segs] = False
1814- if write_prof_data[name]['allow'].get(segs, False): write_prof_data[name]['allow'].pop(segs)
1815- if write_prof_data[name]['deny'].get(segs, False): write_prof_data[name]['deny'].pop(segs)
1816+ if write_prof_data[name]['allow'].get(segs, False):
1817+ write_prof_data[name]['allow'].pop(segs)
1818+ if write_prof_data[name]['deny'].get(segs, False):
1819+ write_prof_data[name]['deny'].pop(segs)
1820 segments['lvar'] = True
1821 write_prof_data[hat]['lvar'].pop(bool_var)
1822 data.append(line)
1823@@ -3712,10 +3730,12 @@
1824 if not segments['lvar'] and True in segments.values():
1825 for segs in list(filter(lambda x: segments[x], segments.keys())):
1826 depth = len(line) - len(line.lstrip())
1827- data += write_methods[segs](write_prof_data[name], int(depth/2))
1828+ data += write_methods[segs](write_prof_data[name], int(depth / 2))
1829 segments[segs] = False
1830- if write_prof_data[name]['allow'].get(segs, False): write_prof_data[name]['allow'].pop(segs)
1831- if write_prof_data[name]['deny'].get(segs, False): write_prof_data[name]['deny'].pop(segs)
1832+ if write_prof_data[name]['allow'].get(segs, False):
1833+ write_prof_data[name]['allow'].pop(segs)
1834+ if write_prof_data[name]['deny'].get(segs, False):
1835+ write_prof_data[name]['deny'].pop(segs)
1836 segments['lvar'] = True
1837 if profile:
1838 write_prof_data[hat]['lvar'].pop(list_var)
1839@@ -3747,7 +3767,7 @@
1840
1841 tmpmode = set()
1842 if user:
1843- tmpmode = str_to_mode('%s::' %mode)
1844+ tmpmode = str_to_mode('%s::' % mode)
1845 else:
1846 tmpmode = str_to_mode(mode)
1847
1848@@ -3764,10 +3784,12 @@
1849 if not segments['path'] and True in segments.values():
1850 for segs in list(filter(lambda x: segments[x], segments.keys())):
1851 depth = len(line) - len(line.lstrip())
1852- data += write_methods[segs](write_prof_data[name], int(depth/2))
1853+ data += write_methods[segs](write_prof_data[name], int(depth / 2))
1854 segments[segs] = False
1855- if write_prof_data[name]['allow'].get(segs, False): write_prof_data[name]['allow'].pop(segs)
1856- if write_prof_data[name]['deny'].get(segs, False): write_prof_data[name]['deny'].pop(segs)
1857+ if write_prof_data[name]['allow'].get(segs, False):
1858+ write_prof_data[name]['allow'].pop(segs)
1859+ if write_prof_data[name]['deny'].get(segs, False):
1860+ write_prof_data[name]['deny'].pop(segs)
1861 segments['path'] = True
1862 write_prof_data[hat][allow]['path'].pop(path)
1863 data.append(line)
1864@@ -3782,10 +3804,12 @@
1865 if not segments['include'] and True in segments.values():
1866 for segs in list(filter(lambda x: segments[x], segments.keys())):
1867 depth = len(line) - len(line.lstrip())
1868- data += write_methods[segs](write_prof_data[name], int(depth/2))
1869+ data += write_methods[segs](write_prof_data[name], int(depth / 2))
1870 segments[segs] = False
1871- if write_prof_data[name]['allow'].get(segs, False): write_prof_data[name]['allow'].pop(segs)
1872- if write_prof_data[name]['deny'].get(segs, False): write_prof_data[name]['deny'].pop(segs)
1873+ if write_prof_data[name]['allow'].get(segs, False):
1874+ write_prof_data[name]['allow'].pop(segs)
1875+ if write_prof_data[name]['deny'].get(segs, False):
1876+ write_prof_data[name]['deny'].pop(segs)
1877 segments['include'] = True
1878 write_prof_data[hat]['include'].pop(include_name)
1879 data.append(line)
1880@@ -3833,16 +3857,18 @@
1881 if not segments['netdomain'] and True in segments.values():
1882 for segs in list(filter(lambda x: segments[x], segments.keys())):
1883 depth = len(line) - len(line.lstrip())
1884- data += write_methods[segs](write_prof_data[name], int(depth/2))
1885+ data += write_methods[segs](write_prof_data[name], int(depth / 2))
1886 segments[segs] = False
1887- if write_prof_data[name]['allow'].get(segs, False): write_prof_data[name]['allow'].pop(segs)
1888- if write_prof_data[name]['deny'].get(segs, False): write_prof_data[name]['deny'].pop(segs)
1889+ if write_prof_data[name]['allow'].get(segs, False):
1890+ write_prof_data[name]['allow'].pop(segs)
1891+ if write_prof_data[name]['deny'].get(segs, False):
1892+ write_prof_data[name]['deny'].pop(segs)
1893 segments['netdomain'] = True
1894
1895 elif RE_PROFILE_CHANGE_HAT.search(line):
1896 matches = RE_PROFILE_CHANGE_HAT.search(line).groups()
1897 hat = matches[0]
1898- hat = strip_quotes(hat)
1899+ hat = strip_quotes(hat)
1900 if not write_prof_data[hat]['declared']:
1901 correct = False
1902 if correct:
1903@@ -3858,7 +3884,7 @@
1904 flags = matches[3]
1905 if not write_prof_data[hat]['flags'] == flags:
1906 correct = False
1907- if not write_prof_data[hat]['declared'] == False:
1908+ if not write_prof_data[hat]['declared'] is False:
1909 correct = False
1910 if not write_filelist['profile'][profile][hat]:
1911 correct = False
1912@@ -3883,10 +3909,10 @@
1913
1914 string += '\n'.join(data)
1915
1916- return string+'\n'
1917+ return string + '\n'
1918
1919 def write_profile_ui_feedback(profile):
1920- UI_Info(_('Writing updated profile for %s.') %profile)
1921+ aaui.UI_Info(_('Writing updated profile for %s.') % profile)
1922 write_profile(profile)
1923
1924 def write_profile(profile):
1925@@ -3896,7 +3922,7 @@
1926 else:
1927 prof_filename = get_profile_filename(profile)
1928
1929- newprof = tempfile.NamedTemporaryFile('w', suffix='~' ,delete=False, dir=profile_dir)
1930+ newprof = tempfile.NamedTemporaryFile('w', suffix='~', delete=False, dir=profile_dir)
1931 if os.path.exists(prof_filename):
1932 shutil.copymode(prof_filename, newprof.name)
1933 else:
1934@@ -3917,7 +3943,7 @@
1935 original_aa[profile] = deepcopy(aa[profile])
1936
1937 def matchliteral(aa_regexp, literal):
1938- p_regexp = '^'+convert_regexp(aa_regexp)+'$'
1939+ p_regexp = '^' + convert_regexp(aa_regexp) + '$'
1940 match = False
1941 try:
1942 match = re.search(p_regexp, literal)
1943@@ -3932,19 +3958,19 @@
1944 m = []
1945
1946 cm, am, m = rematchfrag(profile, 'deny', exec_target)
1947- if cm & AA_MAY_EXEC:
1948+ if cm & apparmor.aamode.AA_MAY_EXEC:
1949 return -1
1950
1951 cm, am, m = match_prof_incs_to_path(profile, 'deny', exec_target)
1952- if cm & AA_MAY_EXEC:
1953+ if cm & apparmor.aamode.AA_MAY_EXEC:
1954 return -1
1955
1956 cm, am, m = rematchfrag(profile, 'allow', exec_target)
1957- if cm & AA_MAY_EXEC:
1958+ if cm & apparmor.aamode.AA_MAY_EXEC:
1959 return 1
1960
1961 cm, am, m = match_prof_incs_to_path(profile, 'allow', exec_target)
1962- if cm & AA_MAY_EXEC:
1963+ if cm & apparmor.aamode.AA_MAY_EXEC:
1964 return 1
1965
1966 return 0
1967@@ -3986,11 +4012,11 @@
1968 net_family_sock = False
1969 if netrules['rule'].get('all', False):
1970 all_net = True
1971- if netrules['rule'].get(family, False) == True:
1972+ if netrules['rule'].get(family, False) is True:
1973 all_net_family = True
1974 if (netrules['rule'].get(family, False) and
1975- type(netrules['rule'][family]) == dict and
1976- netrules['rule'][family][sock_type]):
1977+ type(netrules['rule'][family]) == dict and
1978+ netrules['rule'][family][sock_type]):
1979 net_family_sock = True
1980
1981 if all_net or all_net_family or net_family_sock:
1982@@ -4004,7 +4030,7 @@
1983
1984 prof_filename = get_profile_filename(bin_path)
1985
1986- subprocess.call("cat '%s' | %s -I%s -r >/dev/null 2>&1" %(prof_filename, parser ,profile_dir), shell=True)
1987+ subprocess.call("cat '%s' | %s -I%s -r >/dev/null 2>&1" % (prof_filename, parser, profile_dir), shell=True)
1988
1989 def reload(bin_path):
1990 bin_path = find_executable(bin_path)
1991@@ -4020,7 +4046,7 @@
1992 with open_file_read(filename) as f_in:
1993 data = f_in.readlines()
1994 else:
1995- raise AppArmorException(_('File Not Found: %s') %filename)
1996+ raise AppArmorException(_('File Not Found: %s') % filename)
1997 return data
1998
1999 def load_include(incname):
2000@@ -4029,7 +4055,7 @@
2001 return 0
2002 while load_includeslist:
2003 incfile = load_includeslist.pop(0)
2004- if os.path.isfile(profile_dir+'/'+incfile):
2005+ if os.path.isfile(profile_dir + '/' + incfile):
2006 data = get_include_data(incfile)
2007 incdata = parse_profile_data(data, incfile, True)
2008 #print(incdata)
2009@@ -4040,8 +4066,8 @@
2010 incdata[incname] = hasher()
2011 attach_profile_data(include, incdata)
2012 #If the include is a directory means include all subfiles
2013- elif os.path.isdir(profile_dir+'/'+incfile):
2014- load_includeslist += list(map(lambda x: incfile+'/'+x, os.listdir(profile_dir+'/'+incfile)))
2015+ elif os.path.isdir(profile_dir + '/' + incfile):
2016+ load_includeslist += list(map(lambda x: incfile + '/' + x, os.listdir(profile_dir + '/' + incfile)))
2017
2018 return 0
2019
2020@@ -4069,7 +4095,7 @@
2021 while includelist:
2022 incfile = str(includelist.pop(0))
2023 ret = load_include(incfile)
2024- if not include.get(incfile,{}):
2025+ if not include.get(incfile, {}):
2026 continue
2027 cm, am, m = rematchfrag(include[incfile].get(incfile, {}), allow, path)
2028 #print(incfile, cm, am, m)
2029@@ -4111,7 +4137,7 @@
2030 includelist = [incname]
2031 while includelist:
2032 inc = includelist.pop(0)
2033- cm, am , m = rematchfrag(include[inc][inc], 'allow', path)
2034+ cm, am, m = rematchfrag(include[inc][inc], 'allow', path)
2035 if cm:
2036 combinedmode |= cm
2037 combinedaudit |= am
2038@@ -4129,12 +4155,12 @@
2039 def check_qualifiers(program):
2040 if cfg['qualifiers'].get(program, False):
2041 if cfg['qualifiers'][program] != 'p':
2042- fatal_error(_("%s is currently marked as a program that should not have its own\nprofile. Usually, programs are marked this way if creating a profile for \nthem is likely to break the rest of the system. If you know what you\'re\ndoing and are certain you want to create a profile for this program, edit\nthe corresponding entry in the [qualifiers] section in /etc/apparmor/logprof.conf.") %program)
2043+ fatal_error(_("%s is currently marked as a program that should not have its own\nprofile. Usually, programs are marked this way if creating a profile for \nthem is likely to break the rest of the system. If you know what you\'re\ndoing and are certain you want to create a profile for this program, edit\nthe corresponding entry in the [qualifiers] section in /etc/apparmor/logprof.conf.") % program)
2044 return False
2045
2046 def get_subdirectories(current_dir):
2047 """Returns a list of all directories directly inside given directory"""
2048- if sys.version_info < (3,0):
2049+ if sys.version_info < (3, 0):
2050 return os.walk(current_dir).next()[1]
2051 else:
2052 return os.walk(current_dir).__next__()[1]
2053@@ -4152,7 +4178,7 @@
2054 continue
2055 else:
2056 fi = dirpath + '/' + fi
2057- fi = fi.replace(profile_dir+'/', '', 1)
2058+ fi = fi.replace(profile_dir + '/', '', 1)
2059 load_include(fi)
2060
2061 def glob_common(path):
2062@@ -4178,7 +4204,7 @@
2063 if name1 == name2:
2064 return name1
2065 else:
2066- return '%s^%s' %(name1, name2)
2067+ return '%s^%s' % (name1, name2)
2068
2069 def split_name(name):
2070 names = name.split('^')
2071@@ -4187,7 +4213,7 @@
2072 else:
2073 return names[0], names[1]
2074 def commonprefix(new, old):
2075- match=re.search(r'^([^\0]*)[^\0]*(\0\1[^\0]*)*$', '\0'.join([new, old]))
2076+ match = re.search(r'^([^\0]*)[^\0]*(\0\1[^\0]*)*$', '\0'.join([new, old]))
2077 if match:
2078 return match.groups()[0]
2079 return match
2080@@ -4234,7 +4260,7 @@
2081
2082 profile_dir = conf.find_first_dir(cfg['settings']['profiledir']) or '/etc/apparmor.d'
2083 if not os.path.isdir(profile_dir):
2084- raise AppArmorException('Can\'t find AppArmor profiles' )
2085+ raise AppArmorException('Can\'t find AppArmor profiles')
2086
2087 extra_profile_dir = conf.find_first_dir(cfg['settings']['inactive_profiledir']) or '/etc/apparmor/profiles/extras/'
2088
2089
2090=== modified file 'apparmor/aamode.py'
2091--- apparmor/aamode.py 2013-12-29 09:42:30 +0000
2092+++ apparmor/aamode.py 2014-02-12 00:39:55 +0000
2093@@ -16,7 +16,7 @@
2094 def AA_OTHER(mode):
2095 other = set()
2096 for i in mode:
2097- other.add('::%s'%i)
2098+ other.add('::%s' % i)
2099 return other
2100
2101 def AA_OTHER_REMOVE(mode):
2102@@ -57,14 +57,14 @@
2103 'm': AA_EXEC_MMAP, 'M': AA_EXEC_MMAP,
2104 'i': AA_EXEC_INHERIT, 'I': AA_EXEC_INHERIT,
2105 'u': AA_EXEC_UNCONFINED | AA_EXEC_UNSAFE, # Unconfined + Unsafe
2106- 'U': AA_EXEC_UNCONFINED,
2107- 'p': AA_EXEC_PROFILE | AA_EXEC_UNSAFE, # Profile + unsafe
2108- 'P': AA_EXEC_PROFILE,
2109- 'c': AA_EXEC_CHILD | AA_EXEC_UNSAFE, # Child + Unsafe
2110- 'C': AA_EXEC_CHILD,
2111- 'n': AA_EXEC_NT | AA_EXEC_UNSAFE,
2112- 'N': AA_EXEC_NT
2113- }
2114+ 'U': AA_EXEC_UNCONFINED,
2115+ 'p': AA_EXEC_PROFILE | AA_EXEC_UNSAFE, # Profile + unsafe
2116+ 'P': AA_EXEC_PROFILE,
2117+ 'c': AA_EXEC_CHILD | AA_EXEC_UNSAFE, # Child + Unsafe
2118+ 'C': AA_EXEC_CHILD,
2119+ 'n': AA_EXEC_NT | AA_EXEC_UNSAFE,
2120+ 'N': AA_EXEC_NT
2121+ }
2122
2123 LOG_MODE_RE = re.compile('(r|w|l|m|k|a|x|ix|ux|px|cx|nx|pix|cix|Ix|Ux|Px|PUx|Cx|Nx|Pix|Cix)')
2124 MODE_MAP_RE = re.compile('(r|w|l|m|k|a|x|i|u|p|c|n|I|U|P|C|N)')
2125
2126=== modified file 'apparmor/common.py'
2127--- apparmor/common.py 2014-02-01 01:34:08 +0000
2128+++ apparmor/common.py 2014-02-12 00:39:55 +0000
2129@@ -11,7 +11,6 @@
2130 from __future__ import print_function
2131 import codecs
2132 import collections
2133-import gettext
2134 import glob
2135 import logging
2136 import os
2137@@ -23,6 +22,7 @@
2138
2139 DEBUGGING = False
2140
2141+
2142 #
2143 # Utility classes
2144 #
2145@@ -110,7 +110,7 @@
2146 debug("%s (relative)" % (m))
2147 return False
2148
2149- if '"' in path: # We double quote elsewhere
2150+ if '"' in path: # We double quote elsewhere
2151 return False
2152
2153 try:
2154@@ -166,13 +166,6 @@
2155 # Creates a dictionary for any depth and returns empty dictionary otherwise
2156 return collections.defaultdict(hasher)
2157
2158-def init_translations(domain='apparmor-utils'):
2159- """Installs the translations for the given domain, defaults to apparmor-utils domain"""
2160- #Setup Translation
2161- gettext.translation(domain, fallback=True)
2162- gettext.install(domain)
2163-
2164-
2165 def convert_regexp(regexp):
2166 regex_paren = re.compile('^(.*){([^}]*)}(.*)$')
2167 regexp = regexp.strip()
2168@@ -182,8 +175,8 @@
2169 match = regex_paren.search(new_reg).groups()
2170 prev = match[0]
2171 after = match[2]
2172- p1 = match[1].replace(',','|')
2173- new_reg = prev+'('+p1+')'+after
2174+ p1 = match[1].replace(',', '|')
2175+ new_reg = prev + '(' + p1 + ')' + after
2176
2177 new_reg = new_reg.replace('?', '[^/\000]')
2178
2179@@ -198,7 +191,7 @@
2180 if regexp[0] != '^':
2181 new_reg = '^' + new_reg
2182 if regexp[-1] != '$':
2183- new_reg = new_reg + '$'
2184+ new_reg = new_reg + '$'
2185 return new_reg
2186
2187 def user_perm(prof_dir):
2188@@ -221,7 +214,7 @@
2189 self.debugging = False
2190 if self.debugging not in range(0, 4):
2191 sys.stdout.write('Environment Variable: LOGPROF_DEBUG contains invalid value: %s'
2192- %os.getenv('LOGPROF_DEBUG'))
2193+ % os.getenv('LOGPROF_DEBUG'))
2194 if self.debugging == 0: # debugging disabled, don't need to setup logging
2195 return
2196 if self.debugging == 1:
2197@@ -230,22 +223,21 @@
2198 self.debug_level = logging.INFO
2199 elif self.debugging == 3:
2200 self.debug_level = logging.DEBUG
2201-
2202+
2203 try:
2204 logging.basicConfig(filename=self.logfile, level=self.debug_level,
2205 format='%(asctime)s - %(name)s - %(message)s\n')
2206 except OSError:
2207 # Unable to open the default logfile, so create a temporary logfile and tell use about it
2208 import tempfile
2209- templog = tempfile.NamedTemporaryFile('w', prefix='apparmor', suffix='.log' ,delete=False)
2210- sys.stdout.write("\nCould not open: %s\nLogging to: %s\n"%(self.logfile, templog.name))
2211-
2212+ templog = tempfile.NamedTemporaryFile('w', prefix='apparmor', suffix='.log', delete=False)
2213+ sys.stdout.write("\nCould not open: %s\nLogging to: %s\n" % (self.logfile, templog.name))
2214+
2215 logging.basicConfig(filename=templog.name, level=self.debug_level,
2216 format='%(asctime)s - %(name)s - %(message)s\n')
2217-
2218+
2219 self.logger = logging.getLogger(module_name)
2220
2221-
2222 def error(self, message):
2223 if self.debugging:
2224 self.logger.error(message)
2225
2226=== modified file 'apparmor/config.py'
2227--- apparmor/config.py 2013-12-29 09:42:30 +0000
2228+++ apparmor/config.py 2014-02-12 00:39:55 +0000
2229@@ -20,6 +20,7 @@
2230 import tempfile
2231 if sys.version_info < (3, 0):
2232 import ConfigParser as configparser
2233+
2234 # Class to provide the object[section][option] behavior in Python2
2235 class configparser_py2(configparser.ConfigParser):
2236 def __getitem__(self, section):
2237@@ -34,7 +35,7 @@
2238 import configparser
2239
2240
2241-from apparmor.common import AppArmorException, open_file_read#, warn, msg,
2242+from apparmor.common import AppArmorException, open_file_read # , warn, msg,
2243
2244
2245 # CFG = None
2246@@ -110,7 +111,6 @@
2247 # Replace the target config file with the temporary file
2248 os.rename(config_file.name, filepath)
2249
2250-
2251 def find_first_file(self, file_list):
2252 """Returns name of first matching file None otherwise"""
2253 filename = None
2254@@ -164,7 +164,7 @@
2255 option, value = result[0].split('=')
2256 if '#' in line:
2257 comment = value.split('#', 1)[1]
2258- comment = '#'+comment
2259+ comment = '#' + comment
2260 else:
2261 comment = ''
2262 # If option exists in the new config file
2263@@ -172,7 +172,7 @@
2264 # If value is different
2265 if value != config[''][option]:
2266 value_new = config[''][option]
2267- if value_new != None:
2268+ if value_new is not None:
2269 # Update value
2270 if '"' in line:
2271 value_new = '"' + value_new + '"'
2272@@ -190,7 +190,7 @@
2273 # If option exists in the new config file
2274 if option in options:
2275 # If its no longer option type
2276- if config[''][option] != None:
2277+ if config[''][option] is not None:
2278 value = config[''][option]
2279 line = option + '=' + value + '\n'
2280 f_out.write(line)
2281@@ -204,7 +204,7 @@
2282 for option in options:
2283 value = config[''][option]
2284 # option type entry
2285- if value == None:
2286+ if value is None:
2287 line = option + '\n'
2288 # option=value type entry
2289 else:
2290@@ -273,7 +273,7 @@
2291 if section in sections:
2292 sections.remove(section)
2293 for section in sections:
2294- f_out.write('\n['+section+']\n')
2295+ f_out.write('\n[%s]\n' % section)
2296 options = config.options(section)
2297 for option in options:
2298 line = ' ' + option + ' = ' + config[section][option] + '\n'
2299
2300=== modified file 'apparmor/logparser.py'
2301--- apparmor/logparser.py 2013-09-28 15:13:06 +0000
2302+++ apparmor/logparser.py 2014-02-12 00:39:55 +0000
2303@@ -11,16 +11,22 @@
2304 # GNU General Public License for more details.
2305 #
2306 # ----------------------------------------------------------------------
2307+import gettext
2308 import os
2309 import re
2310 import sys
2311 import time
2312 import LibAppArmor
2313-from apparmor.common import (AppArmorException, error, debug, msg,
2314- open_file_read, valid_path,
2315- hasher, open_file_write, convert_regexp, DebugLogger)
2316-
2317-from apparmor.aamode import *
2318+from apparmor.common import (AppArmorException, error, debug,
2319+ open_file_read, valid_path, hasher,
2320+ open_file_write, convert_regexp,
2321+ DebugLogger)
2322+
2323+from apparmor.aamode import validate_log_mode, log_str_to_mode, hide_log_mode, AA_MAY_EXEC
2324+
2325+# setup module translations
2326+from apparmor.translations import init_translation
2327+_ = init_translation()
2328
2329 class ReadLog:
2330 RE_LOG_v2_6_syslog = re.compile('kernel:\s+(\[[\d\.\s]+\]\s+)?type=\d+\s+audit\([\d\.\:]+\):\s+apparmor=')
2331@@ -31,9 +37,8 @@
2332 PROFILE_MODE_NT_RE = re.compile('r|w|l|m|k|a|x|ix|ux|px|cx|pix|cix|Ux|Px|PUx|Cx|Pix|Cix')
2333 PROFILE_MODE_DENY_RE = re.compile('r|w|l|m|k|a|x')
2334 # Used by netdomain to identify the operation types
2335- OPERATION_TYPES = {
2336- # New socket names
2337- 'create': 'net',
2338+ # New socket names
2339+ OPERATION_TYPES = {'create': 'net',
2340 'post_create': 'net',
2341 'bind': 'net',
2342 'connect': 'net',
2343@@ -47,6 +52,7 @@
2344 'setsockopt': 'net',
2345 'sock_shutdown': 'net'
2346 }
2347+
2348 def __init__(self, pid, filename, existing_profiles, profile_dir, log):
2349 self.filename = filename
2350 self.profile_dir = profile_dir
2351@@ -96,7 +102,7 @@
2352 msg = msg.strip()
2353 self.debug_logger.info('parse_event: %s' % msg)
2354 #print(repr(msg))
2355- if sys.version_info < (3,0):
2356+ if sys.version_info < (3, 0):
2357 # parse_record fails with u'foo' style strings hence typecasting to string
2358 msg = str(msg)
2359 event = LibAppArmor.parse_record(msg)
2360@@ -152,8 +158,7 @@
2361
2362 if ev['aamode']:
2363 # Convert aamode values to their counter-parts
2364- mode_convertor = {
2365- 0: 'UNKNOWN',
2366+ mode_convertor = {0: 'UNKNOWN',
2367 1: 'ERROR',
2368 2: 'AUDITING',
2369 3: 'PERMITTING',
2370@@ -254,30 +259,30 @@
2371 if e['operation'] == 'exec':
2372 if e.get('info', False) and e['info'] == 'mandatory profile missing':
2373 self.add_to_tree(e['pid'], e['parent'], 'exec',
2374- [profile, hat, aamode, 'PERMITTING', e['denied_mask'], e['name'], e['name2']])
2375+ [profile, hat, aamode, 'PERMITTING', e['denied_mask'], e['name'], e['name2']])
2376 elif e.get('name2', False) and '\\null-/' in e['name2']:
2377 self.add_to_tree(e['pid'], e['parent'], 'exec',
2378- [profile, hat, prog, aamode, e['denied_mask'], e['name'], ''])
2379+ [profile, hat, prog, aamode, e['denied_mask'], e['name'], ''])
2380 elif e.get('name', False):
2381 self.add_to_tree(e['pid'], e['parent'], 'exec',
2382- [profile, hat, prog, aamode, e['denied_mask'], e['name'], ''])
2383+ [profile, hat, prog, aamode, e['denied_mask'], e['name'], ''])
2384 else:
2385 self.debug_logger.debug('add_event_to_tree: dropped exec event in %s' % e['profile'])
2386
2387 elif 'file_' in e['operation']:
2388 self.add_to_tree(e['pid'], e['parent'], 'path',
2389- [profile, hat, prog, aamode, e['denied_mask'], e['name'], ''])
2390+ [profile, hat, prog, aamode, e['denied_mask'], e['name'], ''])
2391 elif e['operation'] in ['open', 'truncate', 'mkdir', 'mknod', 'rename_src',
2392 'rename_dest', 'unlink', 'rmdir', 'symlink_create', 'link']:
2393 #print(e['operation'], e['name'])
2394 self.add_to_tree(e['pid'], e['parent'], 'path',
2395- [profile, hat, prog, aamode, e['denied_mask'], e['name'], ''])
2396+ [profile, hat, prog, aamode, e['denied_mask'], e['name'], ''])
2397 elif e['operation'] == 'capable':
2398 self.add_to_tree(e['pid'], e['parent'], 'capability',
2399- [profile, hat, prog, aamode, e['name'], ''])
2400+ [profile, hat, prog, aamode, e['name'], ''])
2401 elif e['operation'] == 'setattr' or 'xattr' in e['operation']:
2402 self.add_to_tree(e['pid'], e['parent'], 'path',
2403- [profile, hat, prog, aamode, e['denied_mask'], e['name'], ''])
2404+ [profile, hat, prog, aamode, e['denied_mask'], e['name'], ''])
2405 elif 'inode_' in e['operation']:
2406 is_domain_change = False
2407 if e['operation'] == 'inode_permission' and (e['denied_mask'] & AA_MAY_EXEC) and aamode == 'PERMITTING':
2408@@ -290,17 +295,17 @@
2409
2410 if is_domain_change:
2411 self.add_to_tree(e['pid'], e['parent'], 'exec',
2412- [profile, hat, prog, aamode, e['denied_mask'], e['name'], e['name2']])
2413+ [profile, hat, prog, aamode, e['denied_mask'], e['name'], e['name2']])
2414 else:
2415 self.add_to_tree(e['pid'], e['parent'], 'path',
2416- [profile, hat, prog, aamode, e['denied_mask'], e['name'], ''])
2417+ [profile, hat, prog, aamode, e['denied_mask'], e['name'], ''])
2418
2419 elif e['operation'] == 'sysctl':
2420 self.add_to_tree(e['pid'], e['parent'], 'path',
2421- [profile, hat, prog, aamode, e['denied_mask'], e['name'], ''])
2422+ [profile, hat, prog, aamode, e['denied_mask'], e['name'], ''])
2423
2424 elif e['operation'] == 'clone':
2425- parent , child = e['pid'], e['task']
2426+ parent, child = e['pid'], e['task']
2427 if not parent:
2428 parent = 'null-complain-profile'
2429 if not hat:
2430@@ -321,10 +326,10 @@
2431
2432 elif self.op_type(e['operation']) == 'net':
2433 self.add_to_tree(e['pid'], e['parent'], 'netdomain',
2434- [profile, hat, prog, aamode, e['family'], e['sock_type'], e['protocol']])
2435+ [profile, hat, prog, aamode, e['family'], e['sock_type'], e['protocol']])
2436 elif e['operation'] == 'change_hat':
2437 self.add_to_tree(e['pid'], e['parent'], 'unknown_hat',
2438- [profile, hat, aamode, hat])
2439+ [profile, hat, aamode, hat])
2440 else:
2441 self.debug_logger.debug('UNHANDLED: %s' % e)
2442
2443@@ -351,7 +356,7 @@
2444 if self.logmark in line:
2445 seenmark = True
2446
2447- self.debug_logger.debug('read_log: seenmark = %s' %seenmark)
2448+ self.debug_logger.debug('read_log: seenmark = %s' % seenmark)
2449 if not seenmark:
2450 continue
2451
2452@@ -382,7 +387,6 @@
2453 return True
2454 return False
2455
2456-
2457 def get_profile_filename(self, profile):
2458 """Returns the full profile name"""
2459 if profile.startswith('/'):
2460@@ -392,4 +396,4 @@
2461 profile = "profile_" + profile
2462 profile = profile.replace('/', '.')
2463 full_profilename = self.profile_dir + '/' + profile
2464- return full_profilename
2465\ No newline at end of file
2466+ return full_profilename
2467
2468=== modified file 'apparmor/severity.py'
2469--- apparmor/severity.py 2014-02-01 00:44:05 +0000
2470+++ apparmor/severity.py 2014-02-12 00:39:55 +0000
2471@@ -14,7 +14,7 @@
2472 from __future__ import with_statement
2473 import os
2474 import re
2475-from apparmor.common import AppArmorException, open_file_read, warn, convert_regexp #, msg, error, debug
2476+from apparmor.common import AppArmorException, open_file_read, warn, convert_regexp # , msg, error, debug
2477
2478 class Severity(object):
2479 def __init__(self, dbname=None, default_rank=10):
2480@@ -31,10 +31,10 @@
2481 if not dbname:
2482 return None
2483
2484- with open_file_read(dbname) as database:#open(dbname, 'r')
2485+ with open_file_read(dbname) as database: # open(dbname, 'r')
2486 for lineno, line in enumerate(database, start=1):
2487- line = line.strip() # or only rstrip and lstrip?
2488- if line == '' or line.startswith('#') :
2489+ line = line.strip() # or only rstrip and lstrip?
2490+ if line == '' or line.startswith('#'):
2491 continue
2492 if line.startswith('/'):
2493 try:
2494@@ -43,7 +43,7 @@
2495 except ValueError:
2496 raise AppArmorException("Insufficient values for permissions in file: %s\n\t[Line %s]: %s" % (dbname, lineno, line))
2497 else:
2498- if read not in range(0, 11) or write not in range(0,11) or execute not in range(0,11):
2499+ if read not in range(0, 11) or write not in range(0, 11) or execute not in range(0, 11):
2500 raise AppArmorException("Inappropriate values for permissions in file: %s\n\t[Line %s]: %s" % (dbname, lineno, line))
2501 path = path.lstrip('/')
2502 if '*' not in path:
2503@@ -67,7 +67,7 @@
2504 except ValueError as e:
2505 error_message = 'No severity value present in file: %s\n\t[Line %s]: %s' % (dbname, lineno, line)
2506 #error(error_message)
2507- raise AppArmorException(error_message) # from None
2508+ raise AppArmorException(error_message) # from None
2509 else:
2510 if severity not in range(0, 11):
2511 raise AppArmorException("Inappropriate severity value present in file: %s\n\t[Line %s]: %s" % (dbname, lineno, line))
2512@@ -83,7 +83,6 @@
2513 warn("unknown capability: %s" % resource)
2514 return self.severity['DEFAULT_RANK']
2515
2516-
2517 def check_subtree(self, tree, mode, sev, segments):
2518 """Returns the max severity from the regex tree"""
2519 if len(segments) == 0:
2520@@ -91,21 +90,21 @@
2521 else:
2522 first = segments[0]
2523 rest = segments[1:]
2524- path = '/'.join([first]+rest)
2525+ path = '/'.join([first] + rest)
2526 # Check if we have a matching directory tree to descend into
2527 if tree.get(first, False):
2528 sev = self.check_subtree(tree[first], mode, sev, rest)
2529 # If severity still not found, match against globs
2530- if sev == None:
2531+ if sev is None:
2532 # Match against all globs at this directory level
2533 for chunk in tree.keys():
2534 if '*' in chunk:
2535 # Match rest of the path
2536- if re.search("^"+chunk, path):
2537+ if re.search("^" + chunk, path):
2538 # Find max rank
2539 if "AA_RANK" in tree[chunk].keys():
2540 for m in mode:
2541- if sev == None or tree[chunk]["AA_RANK"].get(m, -1) > sev:
2542+ if sev is None or tree[chunk]["AA_RANK"].get(m, -1) > sev:
2543 sev = tree[chunk]["AA_RANK"].get(m, None)
2544 return sev
2545
2546@@ -118,12 +117,12 @@
2547 if resource in self.severity['FILES'].keys():
2548 # Find max value among the given modes
2549 for m in mode:
2550- if sev == None or self.severity['FILES'][resource].get(m, -1) > sev:
2551+ if sev is None or self.severity['FILES'][resource].get(m, -1) > sev:
2552 sev = self.severity['FILES'][resource].get(m, None)
2553 else:
2554 # Search regex tree for matching glob
2555 sev = self.check_subtree(self.severity['REGEXPS'], mode, sev, pieces)
2556- if sev == None:
2557+ if sev is None:
2558 # Return default rank if severity cannot be found
2559 return self.severity['DEFAULT_RANK']
2560 else:
2561@@ -146,13 +145,13 @@
2562 rank = None
2563 if '@' in resource:
2564 variable = regex_variable.search(resource).groups()[0]
2565- variable = '@{'+variable+'}'
2566+ variable = '@{%s}' % variable
2567 #variables = regex_variable.findall(resource)
2568 for replacement in self.severity['VARIABLES'][variable]:
2569 resource_replaced = self.variable_replace(variable, replacement, resource)
2570 rank_new = self.handle_variable_rank(resource_replaced, mode)
2571 #rank_new = self.handle_variable_rank(resource.replace('@{'+variable+'}', replacement), mode)
2572- if rank == None or rank_new > rank:
2573+ if rank is None or rank_new > rank:
2574 rank = rank_new
2575 return rank
2576 else:
2577@@ -163,13 +162,13 @@
2578 leading = False
2579 trailing = False
2580 # Check for leading or trailing / that may need to be collapsed
2581- if resource.find("/"+variable) != -1 and resource.find("//"+variable) == -1: # find that a single / exists before variable or not
2582+ if resource.find("/" + variable) != -1 and resource.find("//" + variable) == -1: # find that a single / exists before variable or not
2583 leading = True
2584- if resource.find(variable+"/") != -1 and resource.find(variable+"//") == -1:
2585+ if resource.find(variable + "/") != -1 and resource.find(variable + "//") == -1:
2586 trailing = True
2587- if replacement[0] == '/' and replacement[:2] != '//' and leading: # finds if the replacement has leading / or not
2588+ if replacement[0] == '/' and replacement[:2] != '//' and leading: # finds if the replacement has leading / or not
2589 replacement = replacement[1:]
2590- if replacement[-1] == '/' and replacement[-2:] !='//' and trailing:
2591+ if replacement[-1] == '/' and replacement[-2:] != '//' and trailing:
2592 replacement = replacement[:-1]
2593 return resource.replace(variable, replacement)
2594
2595
2596=== modified file 'apparmor/tools.py'
2597--- apparmor/tools.py 2014-02-01 01:34:08 +0000
2598+++ apparmor/tools.py 2014-02-12 00:39:55 +0000
2599@@ -11,12 +11,17 @@
2600 # GNU General Public License for more details.
2601 #
2602 # ----------------------------------------------------------------------
2603+import gettext
2604 import os
2605 import sys
2606
2607 import apparmor.aa as apparmor
2608 from apparmor.common import user_perm
2609
2610+# setup module translations
2611+from apparmor.translations import init_translation
2612+_ = init_translation()
2613+
2614 class aa_tools:
2615 def __init__(self, tool_name, args):
2616 self.name = tool_name
2617@@ -24,12 +29,12 @@
2618 self.profiling = args.program
2619 self.check_profile_dir()
2620 self.silent = None
2621-
2622+
2623 if tool_name in ['audit', 'complain']:
2624 self.remove = args.remove
2625 elif tool_name == 'disable':
2626 self.revert = args.revert
2627- self.disabledir = apparmor.profile_dir+'/disable'
2628+ self.disabledir = apparmor.profile_dir + '/disable'
2629 self.check_disable_dir()
2630 elif tool_name == 'autodep':
2631 self.force = args.force
2632@@ -41,14 +46,14 @@
2633 if self.profiledir:
2634 apparmor.profile_dir = apparmor.get_full_path(self.profiledir)
2635 if not os.path.isdir(apparmor.profile_dir):
2636- raise apparmor.AppArmorException("%s is not a directory." %self.profiledir)
2637+ raise apparmor.AppArmorException("%s is not a directory." % self.profiledir)
2638
2639 if not user_perm(apparmor.profile_dir):
2640- raise apparmor.AppArmorException("Cannot write to profile directory: %s" %(apparmor.profile_dir))
2641+ raise apparmor.AppArmorException("Cannot write to profile directory: %s" % (apparmor.profile_dir))
2642
2643 def check_disable_dir(self):
2644 if not os.path.isdir(self.disabledir):
2645- raise apparmor.AppArmorException("Can't find AppArmor disable directory %s" %self.disabledir)
2646+ raise apparmor.AppArmorException("Can't find AppArmor disable directory %s" % self.disabledir)
2647
2648 def act(self):
2649 for p in self.profiling:
2650@@ -72,12 +77,12 @@
2651 if program and not program.startswith('/'):
2652 program = apparmor.UI_GetString(_('The given program cannot be found, please try with the fully qualified path name of the program: '), '')
2653 else:
2654- apparmor.UI_Info(_("%s does not exist, please double-check the path.")%p)
2655+ apparmor.UI_Info(_("%s does not exist, please double-check the path.") % p)
2656 sys.exit(1)
2657
2658 if self.name == 'autodep' and program and os.path.exists(program):
2659 self.use_autodep(program)
2660-
2661+
2662 elif program and apparmor.profile_exists(program):
2663 if self.name == 'cleanprof':
2664 self.clean_profile(program, p)
2665@@ -86,21 +91,21 @@
2666 filename = apparmor.get_profile_filename(program)
2667
2668 if not os.path.isfile(filename) or apparmor.is_skippable_file(filename):
2669- apparmor.UI_Info(_('Profile for %s not found, skipping')%p)
2670+ apparmor.UI_Info(_('Profile for %s not found, skipping') % p)
2671
2672 elif self.name == 'disable':
2673 if not self.revert:
2674- apparmor.UI_Info(_('Disabling %s.')%program)
2675+ apparmor.UI_Info(_('Disabling %s.') % program)
2676 self.disable_profile(filename)
2677 else:
2678- apparmor.UI_Info(_('Enabling %s.')%program)
2679+ apparmor.UI_Info(_('Enabling %s.') % program)
2680 self.enable_profile(filename)
2681
2682 elif self.name == 'audit':
2683 if not self.remove:
2684- apparmor.UI_Info(_('Setting %s to audit mode.')%program)
2685+ apparmor.UI_Info(_('Setting %s to audit mode.') % program)
2686 else:
2687- apparmor.UI_Info(_('Removing audit mode from %s.')%program)
2688+ apparmor.UI_Info(_('Removing audit mode from %s.') % program)
2689 apparmor.change_profile_flags(filename, program, 'audit', not self.remove)
2690
2691 elif self.name == 'complain':
2692@@ -111,9 +116,9 @@
2693 #apparmor.set_profile_flags(filename, self.name)
2694 else:
2695 # One simply does not walk in here!
2696- raise apparmor.AppArmorException('Unknown tool: %s'%self.name)
2697+ raise apparmor.AppArmorException('Unknown tool: %s' % self.name)
2698
2699- cmd_info = apparmor.cmd([apparmor.parser, filename, '-I%s'%apparmor.profile_dir, '-R 2>&1', '1>/dev/null'])
2700+ cmd_info = apparmor.cmd([apparmor.parser, filename, '-I%s' % apparmor.profile_dir, '-R 2>&1', '1>/dev/null'])
2701 #cmd_info = apparmor.cmd(['cat', filename, '|', apparmor.parser, '-I%s'%apparmor.profile_dir, '-R 2>&1', '1>/dev/null'])
2702
2703 if cmd_info[0] != 0:
2704@@ -121,9 +126,9 @@
2705
2706 else:
2707 if '/' not in p:
2708- apparmor.UI_Info(_("Can't find %s in the system path list. If the name of the application\nis correct, please run 'which %s' as a user with correct PATH\nenvironment set up in order to find the fully-qualified path and\nuse the full path as parameter.")%(p, p))
2709+ apparmor.UI_Info(_("Can't find %s in the system path list. If the name of the application\nis correct, please run 'which %s' as a user with correct PATH\nenvironment set up in order to find the fully-qualified path and\nuse the full path as parameter.") % (p, p))
2710 else:
2711- apparmor.UI_Info(_("%s does not exist, please double-check the path.")%p)
2712+ apparmor.UI_Info(_("%s does not exist, please double-check the path.") % p)
2713 sys.exit(1)
2714
2715 def clean_profile(self, program, p):
2716@@ -140,12 +145,12 @@
2717 q = apparmor.hasher()
2718 q['title'] = 'Changed Local Profiles'
2719 q['headers'] = []
2720- q['explanation'] = _('The local profile for %s in file %s was changed. Would you like to save it?') %(program, filename)
2721+ q['explanation'] = _('The local profile for %s in file %s was changed. Would you like to save it?') % (program, filename)
2722 q['functions'] = ['CMD_SAVE_CHANGES', 'CMD_VIEW_CHANGES', 'CMD_ABORT']
2723 q['default'] = 'CMD_VIEW_CHANGES'
2724 q['options'] = []
2725 q['selected'] = 0
2726- p =None
2727+ p = None
2728 ans = ''
2729 arg = None
2730 while ans != 'CMD_SAVE_CHANGES':
2731@@ -161,13 +166,13 @@
2732 apparmor.write_profile_ui_feedback(program)
2733 apparmor.reload_base(program)
2734 else:
2735- raise apparmor.AppArmorException(_('The profile for %s does not exists. Nothing to clean.')%p)
2736+ raise apparmor.AppArmorException(_('The profile for %s does not exists. Nothing to clean.') % p)
2737
2738 def use_autodep(self, program):
2739 apparmor.check_qualifiers(program)
2740
2741 if os.path.exists(apparmor.get_profile_filename(program) and not self.force):
2742- apparmor.UI_Info('Profile for %s already exists - skipping.'%program)
2743+ apparmor.UI_Info('Profile for %s already exists - skipping.' % program)
2744 else:
2745 apparmor.autodep(program)
2746 if self.aa_mountpoint:
2747@@ -177,4 +182,4 @@
2748 apparmor.delete_symlink('disable', filename)
2749
2750 def disable_profile(self, filename):
2751- apparmor.create_symlink('disable', filename)
2752\ No newline at end of file
2753+ apparmor.create_symlink('disable', filename)
2754
2755=== modified file 'apparmor/ui.py'
2756--- apparmor/ui.py 2014-02-01 00:44:05 +0000
2757+++ apparmor/ui.py 2014-02-12 00:39:55 +0000
2758@@ -11,12 +11,16 @@
2759 # GNU General Public License for more details.
2760 #
2761 # ----------------------------------------------------------------------
2762+import gettext
2763 import sys
2764-import os
2765 import re
2766 from apparmor.yasti import yastLog, SendDataToYast, GetDataFromYast
2767
2768-from apparmor.common import readkey, AppArmorException, DebugLogger, msg
2769+from apparmor.common import readkey, AppArmorException, DebugLogger
2770+
2771+# setup module translations
2772+from apparmor.translations import init_translation
2773+_ = init_translation()
2774
2775 # Set up UI logger for separate messages from UI module
2776 debug_logger = DebugLogger('UI')
2777@@ -48,14 +52,13 @@
2778 if UI_mode == 'text':
2779 sys.stdout.write('\n' + text + '\n')
2780 else:
2781- SendDataToYast({
2782- 'type': 'dialog-error',
2783+ SendDataToYast({'type': 'dialog-error',
2784 'message': text
2785 })
2786 path, yarg = GetDataFromYast()
2787
2788 def get_translated_hotkey(translated, cmsg=''):
2789- msg = 'PromptUser: '+_('Invalid hotkey for')
2790+ msg = 'PromptUser: ' + _('Invalid hotkey for')
2791
2792 # Originally (\S) was used but with translations it would not work :(
2793 if re.search('\((\S+)\)', translated, re.LOCALE):
2794@@ -64,10 +67,10 @@
2795 if cmsg:
2796 raise AppArmorException(cmsg)
2797 else:
2798- raise AppArmorException('%s %s' %(msg, translated))
2799+ raise AppArmorException('%s %s' % (msg, translated))
2800
2801 def UI_YesNo(text, default):
2802- debug_logger.debug('UI_YesNo: %s: %s %s' %(UI_mode, text, default))
2803+ debug_logger.debug('UI_YesNo: %s: %s %s' % (UI_mode, text, default))
2804 default = default.lower()
2805 ans = None
2806 if UI_mode == 'text':
2807@@ -101,10 +104,9 @@
2808 ans = default
2809
2810 else:
2811- SendDataToYast({
2812- 'type': 'dialog-yesno',
2813- 'question': text
2814- })
2815+ SendDataToYast({'type': 'dialog-yesno',
2816+ 'question': text
2817+ })
2818 ypath, yarg = GetDataFromYast()
2819 ans = yarg['answer']
2820 if not ans:
2821@@ -142,7 +144,7 @@
2822 elif ans == nokey:
2823 ans = 'n'
2824 elif ans == cancelkey:
2825- ans= 'c'
2826+ ans = 'c'
2827 elif ans == 'left':
2828 if default == 'n':
2829 default = 'y'
2830@@ -156,8 +158,7 @@
2831 else:
2832 ans = default
2833 else:
2834- SendDataToYast({
2835- 'type': 'dialog-yesnocancel',
2836+ SendDataToYast({'type': 'dialog-yesnocancel',
2837 'question': text
2838 })
2839 ypath, yarg = GetDataFromYast()
2840@@ -173,8 +174,7 @@
2841 sys.stdout.write('\n' + text)
2842 string = sys.stdin.readline()
2843 else:
2844- SendDataToYast({
2845- 'type': 'dialog-getstring',
2846+ SendDataToYast({'type': 'dialog-getstring',
2847 'label': text,
2848 'default': default
2849 })
2850@@ -201,8 +201,7 @@
2851 if UI_mode == 'text':
2852 UI_Info(message)
2853 else:
2854- SendDataToYast({
2855- 'type': 'dialog-busy-start',
2856+ SendDataToYast({'type': 'dialog-busy-start',
2857 'message': message
2858 })
2859 ypath, yarg = GetDataFromYast()
2860@@ -213,8 +212,7 @@
2861 SendDataToYast({'type': 'dialog-busy-stop'})
2862 ypath, yarg = GetDataFromYast()
2863
2864-CMDS = {
2865- 'CMD_ALLOW': _('(A)llow'),
2866+CMDS = {'CMD_ALLOW': _('(A)llow'),
2867 'CMD_OTHER': _('(M)ore'),
2868 'CMD_AUDIT_NEW': _('Audi(t)'),
2869 'CMD_AUDIT_OFF': _('Audi(t) off'),
2870@@ -307,16 +305,14 @@
2871 sys.exit(0)
2872
2873 def UI_ShortMessage(title, message):
2874- SendDataToYast({
2875- 'type': 'short-dialog-message',
2876+ SendDataToYast({'type': 'short-dialog-message',
2877 'headline': title,
2878 'message': message
2879 })
2880 ypath, yarg = GetDataFromYast()
2881
2882 def UI_LongMessage(title, message):
2883- SendDataToYast({
2884- 'type': 'long-dialog-message',
2885+ SendDataToYast({'type': 'long-dialog-message',
2886 'headline': title,
2887 'message': message
2888 })
2889@@ -356,7 +352,7 @@
2890 keys[key] = cmd
2891
2892 if default and default == cmd:
2893- menutext = '[%s]' %menutext
2894+ menutext = '[%s]' % menutext
2895
2896 menu_items.append(menutext)
2897
2898@@ -392,14 +388,14 @@
2899
2900 prompt = '\n'
2901 if title:
2902- prompt += '= %s =\n\n' %title
2903+ prompt += '= %s =\n\n' % title
2904
2905 if headers:
2906 header_copy = headers[:]
2907 while header_copy:
2908 header = header_copy.pop(0)
2909 value = header_copy.pop(0)
2910- prompt += formatstr %(header+':', value)
2911+ prompt += formatstr % (header + ':', value)
2912 prompt += '\n'
2913
2914 if explanation:
2915@@ -411,12 +407,12 @@
2916 format_option = ' [%s - %s]'
2917 else:
2918 format_option = ' %s - %s '
2919- prompt += format_option %(index+1, option)
2920+ prompt += format_option % (index + 1, option)
2921 prompt += '\n'
2922
2923 prompt += ' / '.join(menu_items)
2924
2925- sys.stdout.write(prompt+'\n')
2926+ sys.stdout.write(prompt + '\n')
2927
2928 ans = getkey().lower()
2929
2930@@ -427,7 +423,7 @@
2931 ans = 'XXXINVALIDXXX'
2932
2933 elif ans == 'down':
2934- if options and selected < len(options)-1:
2935+ if options and selected < len(options) - 1:
2936 selected += 1
2937 ans = 'XXXINVALIDXXX'
2938
2939@@ -446,7 +442,7 @@
2940 ans = 'XXXINVALIDXXX'
2941
2942 if keys.get(ans, False) == 'CMD_HELP':
2943- sys.stdout.write('\n%s\n' %helptext)
2944+ sys.stdout.write('\n%s\n' % helptext)
2945 ans = 'again'
2946
2947 if keys.get(ans, False):
2948
2949=== removed file 'apparmor/writeprofile.py'
2950=== modified file 'apparmor/yasti.py'
2951--- apparmor/yasti.py 2013-09-28 15:13:06 +0000
2952+++ apparmor/yasti.py 2014-02-12 00:39:55 +0000
2953@@ -101,4 +101,3 @@
2954 else:
2955 ret += argref
2956 return ret
2957-

Subscribers

People subscribed via source and target branches