2016-10-01 20:57:09 +02:00
#! /usr/bin/python3
2013-09-28 20:43:06 +05:30
# ----------------------------------------------------------------------
# Copyright (C) 2013 Kshitij Gupta <kgupta8592@gmail.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# ----------------------------------------------------------------------
2013-08-26 00:23:59 +05:30
import argparse
import atexit
2013-08-21 11:26:09 +05:30
import os
import re
2013-08-26 00:23:59 +05:30
import subprocess
import sys
2013-08-21 11:26:09 +05:30
import apparmor.aa as apparmor
2014-03-06 10:22:26 -08:00
import apparmor.ui as aaui
2021-08-24 22:31:11 +02:00
from apparmor.common import AppArmorException, warn
2013-08-21 11:26:09 +05:30
2015-07-06 22:02:34 +02:00
# setup exception handling
from apparmor.fail import enable_aa_exception_handler
enable_aa_exception_handler()
2014-02-10 22:15:05 -08:00
# setup module translations
2014-02-11 16:23:21 -08:00
from apparmor.translations import init_translation
_ = init_translation()
2014-02-10 22:15:05 -08:00
2013-08-21 11:26:09 +05:30
def sysctl_read(path):
value = None
with open(path, 'r') as f_in:
value = int(f_in.readline())
return value
def sysctl_write(path, value):
2014-06-09 23:47:36 +02:00
if value is None:
warn('Not writing invalid value "None" to %s'%path)
2013-08-21 11:26:09 +05:30
return
with open(path, 'w') as f_out:
f_out.write(str(value))
def last_audit_entry_time():
2015-02-20 21:36:55 +01:00
out = subprocess.check_output(['tail', '-1', apparmor.logfile])
2013-08-21 11:26:09 +05:30
logmark = None
2014-05-21 21:42:43 +02:00
out = out.decode('ascii')
2014-03-20 00:10:13 +01:00
if re.search('^.*msg\=audit\((\d+\.\d+\:\d+).*\).*$', out):
logmark = re.search('^.*msg\=audit\((\d+\.\d+\:\d+).*\).*$', out).groups()[0]
2013-08-21 11:26:09 +05:30
else:
logmark = ''
return logmark
def restore_ratelimit():
2018-08-05 14:46:13 +02:00
try:
sysctl_write(ratelimit_sysctl, ratelimit_saved)
except PermissionError:
if ratelimit_saved != sysctl_read(ratelimit_sysctl):
raise # happens only if a) running under lxd and b) something changed the ratelimit since starting aa-genprof
2013-08-21 11:26:09 +05:30
2013-09-22 15:25:20 +05:30
parser = argparse.ArgumentParser(description=_('Generate profile for the given program'))
parser.add_argument('-d', '--dir', type=str, help=_('path to profiles'))
parser.add_argument('-f', '--file', type=str, help=_('path to logfile'))
parser.add_argument('program', type=str, help=_('name of program to profile'))
2017-06-15 18:22:43 +02:00
parser.add_argument('-j', '--json', action="store_true", help=_('Input and Output in JSON'))
2020-10-25 15:48:41 +01:00
parser.add_argument('--configdir', type=str, help=argparse.SUPPRESS)
2013-08-21 11:26:09 +05:30
args = parser.parse_args()
2017-06-15 18:22:43 +02:00
if args.json:
aaui.set_json_mode()
2013-08-21 11:26:09 +05:30
profiling = args.program
2020-10-25 15:48:41 +01:00
apparmor.init_aa(confdir=args.configdir, profiledir=args.dir)
2015-02-20 21:36:55 +01:00
apparmor.set_logfile(args.file)
2013-12-20 03:12:58 +05:30
2013-08-21 11:26:09 +05:30
aa_mountpoint = apparmor.check_for_apparmor()
if not aa_mountpoint:
2021-08-24 22:31:11 +02:00
raise AppArmorException(_('It seems AppArmor was not started. Please enable AppArmor and try again.'))
2013-08-21 11:26:09 +05:30
program = None
#if os.path.exists(apparmor.which(profiling.strip())):
if os.path.exists(profiling):
program = apparmor.get_full_path(profiling)
else:
if '/' not in profiling:
which = apparmor.which(profiling)
if which:
program = apparmor.get_full_path(which)
if not program or not os.path.exists(program):
if '/' not in profiling:
2021-08-24 22:31:11 +02:00
raise AppArmorException(_("Can't find %(profiling)s in the system path list. If the name of the application\nis correct, please run 'which %(profiling)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.") % { 'profiling': profiling })
2013-08-21 11:26:09 +05:30
else:
2021-08-24 22:31:11 +02:00
raise AppArmorException(_('%s does not exists, please double-check the path.') %profiling)
2013-08-21 11:26:09 +05:30
# Check if the program has been marked as not allowed to have a profile
apparmor.check_qualifiers(program)
apparmor.loadincludes()
2020-05-05 23:56:55 +02:00
apparmor.read_profiles(True)
2018-10-22 22:51:34 +02:00
profile_filename = apparmor.get_profile_filename_from_attachment(program, True)
2013-08-21 11:26:09 +05:30
if os.path.exists(profile_filename):
2013-09-23 21:00:36 +05:30
apparmor.helpers[program] = apparmor.get_profile_flags(profile_filename, program)
2013-08-21 11:26:09 +05:30
else:
apparmor.autodep(program)
apparmor.helpers[program] = 'enforce'
if apparmor.helpers[program] == 'enforce':
apparmor.complain(program)
apparmor.reload(program)
# When reading from syslog, it is possible to hit the default kernel
# printk ratelimit. This will result in audit entries getting skipped,
# making profile generation inaccurate. When using genprof, disable
# the printk ratelimit, and restore it on exit.
ratelimit_sysctl = '/proc/sys/kernel/printk_ratelimit'
ratelimit_saved = sysctl_read(ratelimit_sysctl)
2018-08-05 14:46:13 +02:00
try:
sysctl_write(ratelimit_sysctl, 0)
except PermissionError: # will fail in lxd
warn("Can't set printk_ratelimit, some events might be lost")
2013-08-21 11:26:09 +05:30
atexit.register(restore_ratelimit)
2018-09-13 16:45:39 +00:00
aaui.UI_Info(_('\nBefore you begin, you may wish to check if a\nprofile already exists for the application you\nwish to confine. See the following wiki page for\nmore information:')+'\nhttps://gitlab.com/apparmor/apparmor/wikis/Profiles')
2013-08-21 11:26:09 +05:30
syslog = True
logmark = ''
done_profiling = False
if os.path.exists('/var/log/audit/audit.log'):
syslog = False
while not done_profiling:
if syslog:
logmark = subprocess.check_output(['date | md5sum'], shell=True)
logmark = logmark.decode('ascii').strip()
logmark = re.search('^([0-9a-f]+)', logmark).groups()[0]
2015-10-20 22:03:58 +02:00
t=subprocess.call("%s -p kern.warn 'GenProf: %s'"%(apparmor.logger_path(), logmark), shell=True)
2013-08-21 11:26:09 +05:30
else:
logmark = last_audit_entry_time()
2013-09-22 22:51:30 +05:30
2014-10-09 01:37:18 +05:30
q = aaui.PromptQuestion()
q.headers = [_('Profiling'), program]
q.functions = ['CMD_SCAN', 'CMD_FINISHED']
q.default = 'CMD_SCAN'
2017-07-14 22:32:15 +02:00
q.explanation = _('Please start the application to be profiled in\nanother window and exercise its functionality now.\n\nOnce completed, select the "Scan" option below in \norder to scan the system logs for AppArmor events. \n\nFor each AppArmor event, you will be given the \nopportunity to choose whether the access should be \nallowed or denied.')
2014-10-09 01:37:18 +05:30
ans, arg = q.promptUser('noexit')
2013-09-22 22:51:30 +05:30
2013-08-21 11:26:09 +05:30
if ans == 'CMD_SCAN':
2020-05-05 23:56:55 +02:00
apparmor.do_logprof_pass(logmark)
2013-08-21 11:26:09 +05:30
else:
done_profiling = True
for p in sorted(apparmor.helpers.keys()):
if apparmor.helpers[p] == 'enforce':
2014-02-13 08:20:59 -08:00
apparmor.enforce(p)
apparmor.reload(p)
2013-08-21 11:26:09 +05:30
2014-03-06 10:22:26 -08:00
aaui.UI_Info(_('\nReloaded AppArmor profiles in enforce mode.'))
2018-09-13 16:45:39 +00:00
aaui.UI_Info(_('\nPlease consider contributing your new profile!\nSee the following wiki page for more information:')+'\nhttps://gitlab.com/apparmor/apparmor/wikis/Profiles\n')
2014-03-06 10:22:26 -08:00
aaui.UI_Info(_('Finished generating profile for %s.')%program)
2013-08-21 11:26:09 +05:30
sys.exit(0)