Merge branch 'cboltz-drop-deprecated' into 'master'

drop deprecated perl code

* drop repair_obsolete_profiles (updated profiles for abstraction renames pre-2006)
* drop ancient perl aa-* tools and their modules (rewritten to python in 2.9)
* drop rc.aaeventd.{redhat,suse} initscripts (aaeventd was dropped long ago, therefore we don't need to keep its initscripts)

See merge request apparmor/apparmor!423

Acked-by: John Johansen <john.johansen@canonical.com>
This commit is contained in:
Christian Boltz 2019-09-25 20:32:20 +00:00
commit 0b94cbe516
20 changed files with 0 additions and 13052 deletions

View file

@ -1,137 +0,0 @@
#!/bin/sh
# ----------------------------------------------------------------------
# Copyright (c) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007
# NOVELL (All rights reserved)
#
# 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 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, contact Novell, Inc.
# ----------------------------------------------------------------------
# rc.apparmor by Steve Beattie
#
# /etc/init.d/aaeventd
# and its symbolic link
# /sbin/rcaaeventd
#
# chkconfig: 2345 01 99
# description: AppArmor Notification and Reporting daemon
#
### BEGIN INIT INFO
# Provides: aaeventd
# Required-Start: apparmor
# Required-Stop:
# Default-Start: 2 3 5
# Default-Stop:
# Short-Description: AppArmor Notification and Reporting
# Description: AppArmor Notification and Reporting daemon
### END INIT INFO
APPARMOR_FUNCTIONS=/lib/apparmor/rc.apparmor.functions
# source function library
if [ -f /etc/init.d/functions ]; then
. /etc/init.d/functions
elif [ -f /etc/rc.d/init.d/functions ]; then
. /etc/rc.d/init.d/functions
elif [ -f /lib/lsb/init-functions ]; then
. /lib/lsb/init-functions
else
exit 0
fi
sd_log_success_msg() {
echo -n "$*"
success
echo
}
sd_log_warning_msg() {
echo -n "$*"
warning
echo
}
sd_log_skipped_msg() {
echo -n "$*"
warning
echo
}
sd_log_failure_msg() {
echo -n "$*"
failure
echo
}
sd_action() {
STRING=$1
shift
action "${STRING} " "$@"
return $?
}
start_aa_event() {
if [ -x "$AA_EV_BIN" -a "${APPARMOR_ENABLE_AAEVENTD}" = "yes" ] ; then
sd_action "Starting AppArmor Event daemon" daemon --pidfile $AA_EV_PIDFILE $AA_EV_BIN -p $AA_EV_PIDFILE
elif [ -x "$SD_EV_BIN" -a "${APPARMOR_ENABLE_AAEVENTD}" = "yes" ] ; then
sd_action "Starting AppArmor Event daemon" daemon --pidfile $SD_EV_PIDFILE $SD_EV_BIN -p $SD_EV_PIDFILE
fi
}
stop_aa_event() {
if [ -x "$AA_EV_BIN" -a -f "$AA_EV_PIDFILE" ] ; then
sd_action "Shutting down AppArmor Event daemon" killproc -p $AA_EV_PIDFILE -INT $AA_EV_BIN
fi
if [ -f "$SD_EV_PIDFILE" ] ; then
sd_action "Shutting down AppArmor Event daemon" killproc -p $SD_EV_PIDFILE -INT $SD_EV_BIN
fi
}
usage() {
echo "Usage: $0 {start|stop|restart|try-restart|reload|force-reload|status}"
}
# source apparmor function library
if [ -f "${APPARMOR_FUNCTIONS}" ]; then
. ${APPARMOR_FUNCTIONS}
else
sd_log_failure_msg "Unable to find AppArmor initscript functions"
exit 1
fi
case "$1" in
start)
start_aa_event
rc=$?
;;
stop)
stop_aa_event
rc=$?
;;
restart|reload|force-reload|try-restart)
stop_aa_event
start_aa_event
rc=$?
;;
status)
echo -n "Checking for service AppArmor Event daemon:"
if [ "${APPARMOR_ENABLE_AAEVENTD}" = "yes" ]; then
/sbin/checkproc -p $AA_EV_PIDFILE $AA_EV_BIN
rc_status -v
else
rc_status -u
fi
;;
*)
usage
exit 1
;;
esac
exit $rc

View file

@ -1,133 +0,0 @@
#!/bin/sh
# ----------------------------------------------------------------------
# Copyright (c) 1999, 2000, 2001, 2002, 2003 2004, 2005, 2006, 2007
# NOVELL (All rights reserved)
#
# 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 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, contact Novell, Inc.
# ----------------------------------------------------------------------
# rc.apparmor by Steve Beattie
#
# /etc/init.d/aaeventd
# and its symbolic link
# /sbin/rcaaeventd
#
# chkconfig: 2345 01 99
# description: AppArmor Notification and Reporting daemon
#
### BEGIN INIT INFO
# Provides: aaeventd
# Required-Start: apparmor
# Required-Stop: $null
# Default-Start: 2 3 5
# Default-Stop:
# Short-Description: AppArmor Notification and Reporting
# Description: AppArmor Notification and Reporting daemon
### END INIT INFO
APPARMOR_FUNCTIONS=/lib/apparmor/rc.apparmor.functions
# source function library
if [ -f /etc/init.d/functions ]; then
. /etc/init.d/functions
elif [ -f /etc/rc.d/init.d/functions ]; then
. /etc/rc.d/init.d/functions
elif [ -f /lib/lsb/init-functions ]; then
. /lib/lsb/init-functions
else
exit 0
fi
# Ugh, SUSE doesn't implement action
sd_action() {
STRING=$1
shift
"$@"
rc=$?
if [ $rc -eq 0 ] ; then
log_success_msg $"$STRING "
else
log_failure_msg $"$STRING "
fi
return $rc
}
sd_log_success_msg() {
log_success_msg $*
}
sd_log_warning_msg() {
log_warning_msg $*
}
sd_log_failure_msg() {
log_failure_msg $*
}
usage() {
echo "Usage: $0 {start|stop|restart|try-restart|reload|force-reload|status}"
}
start_aa_event() {
if [ -x "$AA_EV_BIN" -a "${APPARMOR_ENABLE_AAEVENTD}" = "yes" ] ; then
sd_action "Starting AppArmor Event daemon" startproc -p $AA_EV_PIDFILE $AA_EV_BIN -p $AA_EV_PIDFILE
elif [ -x "$SD_EV_BIN" -a "${APPARMOR_ENABLE_AAEVENTD}" = "yes" ] ; then
sd_action "Starting AppArmor Event daemon" startproc -p $SD_EV_PIDFILE $SD_EV_BIN -p $SD_EV_PIDFILE
fi
}
stop_aa_event() {
if [ -x "$AA_EV_BIN" -a -f "$AA_EV_PIDFILE" ] ; then
sd_action "Shutting down AppArmor Event daemon" killproc -G -p $AA_EV_PIDFILE -INT $AA_EV_BIN
fi
if [ -f "$SD_EV_PIDFILE" ] ; then
sd_action "Shutting down AppArmor Event daemon" killproc -G -p $SD_EV_PIDFILE -INT $SD_EV_BIN
fi
}
# source apparmor function library
if [ -f "${APPARMOR_FUNCTIONS}" ]; then
. ${APPARMOR_FUNCTIONS}
else
sd_log_failure_msg "Unable to find AppArmor initscript functions"
exit 1
fi
case "$1" in
start)
start_aa_event
rc=$?
;;
stop)
stop_aa_event
rc=$?
;;
restart|reload|force-reload|try-restart)
stop_aa_event
start_aa_event
rc=$?
;;
status)
echo -n "Checking for service AppArmor Event daemon:"
if [ "${APPARMOR_ENABLE_AAEVENTD}" = "yes" ]; then
/sbin/checkproc -p $AA_EV_PIDFILE $AA_EV_BIN
rc_status -v
else
rc_status -u
fi
;;
*)
usage
exit 1
;;
esac
exit $rc

File diff suppressed because it is too large Load diff

View file

@ -1,124 +0,0 @@
# ----------------------------------------------------------------------
# Copyright (c) 2006 Novell, Inc. All Rights Reserved.
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, contact Novell, Inc.
#
# To contact Novell about this file by physical or electronic mail,
# you may find current contact information at www.novell.com.
# ----------------------------------------------------------------------
package Immunix::Config;
use strict;
use warnings;
use Carp;
use Cwd qw(cwd realpath);
use File::Basename;
use File::Temp qw/ tempfile tempdir /;
use Data::Dumper;
use Locale::gettext;
use POSIX;
require Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(
read_config
write_config
find_first_file
find_first_dir
);
our $confdir = "/etc/apparmor";
# config vars
our $cfg;
our $repo_cfg;
sub read_config {
my $filename = shift;
my $config;
if (open(CONF, "$confdir/$filename")) {
my $which;
while (<CONF>) {
chomp;
# ignore comments
next if /^\s*#/;
if (m/^\[(\S+)\]/) {
$which = $1;
} elsif (m/^\s*(\S+)\s*=\s*(.*)\s*$/) {
my ($key, $value) = ($1, $2);
$config->{$which}{$key} = $value;
}
}
close(CONF);
}
# LP: #692406
# Explicitly disable the repository until there is an alternative, since
# the OpenSUSE site went away
if ($filename eq "repository.conf") {
$config->{repository}{enabled} = "no";
}
return $config;
}
sub write_config {
my ($filename, $config) = @_;
if (open(my $CONF, ">$confdir/$filename")) {
for my $section (sort keys %$config) {
print $CONF "[$section]\n";
for my $key (sort keys %{$config->{$section}}) {
print $CONF " $key = $config->{$section}{$key}\n"
if ($config->{$section}{$key});
}
}
chmod(0600, $CONF);
close($CONF);
} else {
die "Can't write config file $filename: $!";
}
}
sub find_first_file {
my $list = shift;
return if ( not defined $list );
my $filename;
for my $f (split(/\s+/, $list)) {
if (-f $f) {
$filename = $f;
last;
}
}
return $filename;
}
sub find_first_dir {
my $list = shift;
return if ( not defined $list );
my $dirname;
for my $f (split(/\s+/, $list)) {
if (-d $f) {
$dirname = $f;
last;
}
}
return $dirname;
}
1;

File diff suppressed because it is too large Load diff

View file

@ -1,354 +0,0 @@
# ----------------------------------------------------------------------
# Copyright (c) 2008 Dominic Reynolds
#
# 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.
#
#
# ----------------------------------------------------------------------
package Immunix::Repository;
use strict;
use warnings;
use Carp;
use Cwd qw(cwd realpath);
use Data::Dumper;
use File::Basename;
use File::Temp qw/ tempfile tempdir /;
use Immunix::Config;
use Locale::gettext;
use POSIX;
use RPC::XML;
use RPC::XML::Client;
require Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(
get_repo_client
did_result_succeed
get_result_error
user_login
user_register
upload_profile
fetch_profile_by_id
fetch_profiles_by_user
fetch_profiles_by_name
fetch_profiles_by_name_and_user
fetch_newer_profile
get_repo_config
set_repo_config
);
our %clients;
our %uid2login;
our $DEBUGGING = 0;
our $repo_cfg;
our $aa_cfg;
sub get_repo_client ($) {
my $repo_url = shift;
unless ( $clients{$repo_url} ) {
$clients{$repo_url} = new RPC::XML::Client $repo_url;
}
return $clients{$repo_url};
}
sub did_result_succeed {
my $result = shift;
my $ref = ref $result;
return ($ref && $ref ne "RPC::XML::fault") ? 1 : 0;
}
sub get_result_error {
my $result = shift;
if (ref $result) {
if (ref $result eq "RPC::XML::fault") {
$result = $result->string;
} else {
$result = $$result;
}
}
return $result;
}
sub user_login ($$$) {
my ($repo_url,$user,$pass) = @_;
my ($status,$detail);
my $repo_client = get_repo_client( $repo_url );
if ( $repo_client ) {
my $res = $repo_client->send_request('LoginConfirm', $user, $pass);
if (did_result_succeed($res)) {
$status = 1;
$detail = "";
} else {
$status = 0;
$detail = get_result_error($res);
}
}
return $status,$detail;
}
sub user_register ($$$$) {
my ($repo_url,$user,$pass,$email) = @_;
my $repo_client = get_repo_client( $repo_url );
my ($status,$detail);
if ( $repo_client ) {
my $res = $repo_client->send_request('Signup', $user, $pass, $email);
if (did_result_succeed($res)) {
$status = 1;
$detail = "";
} else {
$status = 0;
$detail = get_result_error($res);
}
}
return $status,$detail;
}
sub upload_profile ($$$$$$$) {
my ($repo_url,$user,$pass,$distro,$pname,$profile,$changelog) = @_;
my ($status,$detail);
my $repo_client = get_repo_client( $repo_url );
my $res = $repo_client->send_request( 'Create', $user, $pass, $distro,
$pname, $profile, $changelog);
if (did_result_succeed($res)) {
$detail = $res->value;
$status = 1;
} else {
$detail = get_result_error($res);
$status = 0;
}
return $status,$detail;
}
sub fetch_profile_by_id ($$) {
my ($repo_url,$id) = @_;
my $repo_client = get_repo_client( $repo_url );
my $repo_profile;
my ($status,$detail);
my $res = $repo_client->send_request('Show', $id);
if (did_result_succeed($res)) {
$status = 1;
$detail = $res->value();
} else {
$status = 0;
$detail = get_result_error($res);
}
return $status, $detail;
}
sub fetch_profiles ($$$$) {
my ($repo_url,$distro,$username,$fqdn) = @_;
my $p_hash = {};
my ($status,$detail);
my $repo_client = get_repo_client( $repo_url );
my $res =
$repo_client->send_request('FindProfiles', $distro, $fqdn, $username);
if (did_result_succeed($res)) {
$status = 1;
for my $p ( @$res ) {
my $p_repo = $p->{profile}->value();
$p_repo =~ s/flags=\(complain\)// if ( $p_repo ); #strip complain flag
$p->{profile} = $p_repo;
$p->{user_id} = $p->{user_id}->value();
$p->{id} = $p->{id}->value();
$p->{name} = $p->{name}->value();
$p->{created_at} = $p->{created_at}->value();
$p->{downloaded_count} = $p->{downloaded_count}->value();
}
$detail = $res;
} else {
$status = 0;
$detail = get_result_error($res);
}
return $status,$detail;
}
sub fetch_profiles_by_user ($$$) {
my ($repo_url,$distro,$username) = @_;
my $p_hash = {};
my ($status,$detail) = fetch_profiles( $repo_url, $distro, $username, "" );
if ( $status ) {
for my $p ( @$detail ) {
my $p_repo = $p->{profile};
if ($p_repo ne "") {
$p->{username} = $username;
$p_hash->{$p->{name}} = $p;
}
}
} else {
return ($status,$detail);
}
return($status,$p_hash);
}
sub fetch_profiles_by_name_and_user ($$$$) {
my ($repo_url,$distro,$fqdbin, $username) = @_;
my $p_hash = {};
my ($status,$detail) = fetch_profiles( $repo_url, $distro, $username, $fqdbin );
if ( $status ) {
for my $p ( @$detail ) {
my $p_repo = $p->{profile}?$p->{profile}:"";
$p_hash->{$p->{name}} = $p if ($p_repo ne "");
}
} else {
return ($status,$detail);
}
return($status,$p_hash);
}
sub fetch_profiles_by_name ($$$) {
my ($repo_url,$distro,$fqdbin) = @_;
my ($status,$detail,$data);
$detail = {};
($status,$data) = fetch_profiles( $repo_url, $distro, "", $fqdbin);
if ($status) {
my @uids;
for my $p (@$data) {
push @uids, $p->{user_id};
}
my ($status_unames,$unames) = fetch_usernames_from_uids($repo_url, @uids);
if ( $status_unames ) {
for my $p (@$data) {
if ( $unames->{$p->{user_id}} ) {
$p->{username} = $unames->{$p->{user_id}};
} else {
$p->{username} = "unkown-" . $p->{user_id};
}
}
} else {
print STDOUT "ERROR UID\n";
}
for my $p (@$data) {
$p->{profile_type} = "REPOSITORY";
$detail->{$p->{username}} = $p;
}
} else {
$detail = $data;
}
return $status,$detail;
}
sub fetch_newer_profile ($$$$$) {
my ($repo_url,$distro,$user,$id,$profile) = @_;
my $repo_client = get_repo_client( $repo_url );
my $p;
my ($status,$detail);
if ($repo_client) {
my $res =
$repo_client->send_request('FindProfiles', $distro, $profile, $user);
if (did_result_succeed($res)) {
my @profiles;
my @profile_list = @{$res->value};
$status = 1;
if (@profile_list) {
if ($profile_list[0]->{id} > $id) {
$p = $profile_list[0];
}
}
$detail = $p;
} else {
$status = 0;
$detail = get_result_error($res);
}
}
return $status,$detail;
}
sub fetch_usernames_from_uids ($) {
my ($repo_url,@searchuids) = @_;
my ($status,$result) = (1,{});
my @uids;
for my $uid ( @searchuids ) {
if ( $uid2login{$uid} ) {
$result->{$uid} = $uid2login{$uid};
} else {
push @uids, $uid;
}
}
if (@uids) {
my $repo_client = get_repo_client( $repo_url );
#RPC::XML will serialize the array into XML with the is_utf8 flag set
#which causes, HTTP:Message to fail. Looping on the array elements
#stops this from happening, and since these are all numbers it
#will not cause problems.
for my $foo (@uids) {
Encode::_utf8_off($foo);
}
my $res = $repo_client->send_request('LoginNamesFromUserIds', [@uids]);
if (did_result_succeed($res)) {
my @usernames = @{ $res->value };
for my $uid (@uids) {
my $username = shift @usernames;
$uid2login{$uid} = $username;
$result->{$uid} = $uid2login{$uid};
}
} else {
$status = 0;
$result = get_result_error($res);
}
}
return $status,$result;
}
sub get_repo_config {
unless ( $repo_cfg ) {
$repo_cfg = Immunix::Config::read_config("repository.conf");
}
unless ( $aa_cfg ) {
$aa_cfg = Immunix::Config::read_config("logprof.conf");
}
return {
"url" => $aa_cfg->{repository}{url},
"distro" => $aa_cfg->{repository}{distro},
"enabled" => $repo_cfg->{repository}{enabled},
"upload" => $repo_cfg->{repository}{upload},
"user" => $repo_cfg->{repository}{user},
"password" => $repo_cfg->{repository}{pass},
"email" => $repo_cfg->{repository}{email}
};
}
sub set_repo_config ($) {
my $cfg = shift;
my ($url,$distro,$enabled,$upload,$user,$pass);
unless ( $repo_cfg ) {
$repo_cfg = Immunix::Config::read_config("repository.conf");
}
unless ( $aa_cfg ) {
$aa_cfg = Immunix::Config::read_config("logprof.conf");
}
$repo_cfg->{repository}{enabled} = $cfg->{enabled} if ( $cfg->{enabled} );
$repo_cfg->{repository}{upload} = $cfg->{upload} if ( $cfg->{upload} );
$repo_cfg->{repository}{user} = $cfg->{user} if ( $cfg->{user} );
$repo_cfg->{repository}{pass} = $cfg->{password}if ( $cfg->{password} );
$repo_cfg->{repository}{email} = $cfg->{email} if ( $cfg->{email} );
$aa_cfg->{repository}{distro} = $cfg->{distro} if ( $cfg->{distro} );
$aa_cfg->{repository}{url} = $cfg->{url} if ( $cfg->{url} );
write_config("repository.conf", $repo_cfg);
write_config("logprof.conf", $aa_cfg);
}
1;

View file

@ -1,221 +0,0 @@
# ------------------------------------------------------------------
#
# Copyright (C) 2005-2006 Novell/SUSE
#
# 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 published by the Free Software Foundation.
#
# ------------------------------------------------------------------
package Immunix::Severity;
use strict;
use Data::Dumper;
my ($debug) = 0;
sub debug {
print @_ if $debug;
}
sub new {
my $self = {};
$self->{DATABASENAME} = undef;
$self->{CAPABILITIES} = {};
$self->{FILES} = {};
$self->{REGEXPS} = {};
$self->{DEFAULT_RANK} = 10;
bless($self);
shift;
$self->init(@_) if @_;
return $self;
}
sub init ($;$) {
my ($self, $resource, $read, $write, $execute, $severity);
$self = shift;
$self->{DATABASENAME} = shift;
$self->{DEFAULT_RANK} = shift if defined $_[0];
open(DATABASE, $self->{DATABASENAME})
or die "Could not open severity db $self->{DATABASENAME}: $!\n";
while (<DATABASE>) {
chomp();
next if m/^\s*#/;
next if m/^\s*$/;
# leading whitespace is fine; maybe it shouldn't be?
if (/^\s*\/(\S+)\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
my ($path, $read, $write, $execute) = ($1, $2, $3, $4);
if (index($path, "*") == -1) {
$self->{FILES}{$path} = {
r => $read,
w => $write,
x => $execute
};
} else {
my $ptr = $self->{REGEXPS};
my @pieces = split(/\//, $path);
while (my $piece = shift @pieces) {
if (index($piece, "*") != -1) {
my $path = join("/", $piece, @pieces);
my $regexp = convert_regexp($path);
$ptr->{$regexp}{SD_RANK} = {
r => $read,
w => $write,
x => $execute
};
last;
} else {
$ptr->{$piece} = {} unless exists $ptr->{$piece};
$ptr = $ptr->{$piece};
}
}
}
} elsif (m|^\s*CAP|) {
($resource, $severity) = split;
$self->{CAPABILITIES}{$resource} = $severity;
} else {
print "unexpected database line: $_\n";
}
}
close(DATABASE);
debug Dumper($self);
return $self;
}
#rank:
# handle capability
# handle file
#
# handle capability
# if the name is in the database, return it
# otherwise, send a diagnostic message to stderr and return the default
#
# handle file
# initialize the current return value to 0
# loop over each entry in the database;
# find the max() value for each mode that matches and set a 'found' flag
# if the found flag has not been set, return the default;
# otherwise, return the maximum from the database
sub handle_capability ($) {
my ($self, $resource) = @_;
my $ret = $self->{CAPABILITIES}{$resource};
if (!defined($ret)) {
return "unexpected capability rank input: $resource\n";
}
return $ret;
}
sub check_subtree {
my ($tree, $mode, $sev, $first, @rest) = @_;
# reassemble the remaining path from this directory level
my $path = join("/", $first, @rest);
# first check if we have a literal directory match to descend into
if ($tree->{$first}) {
$sev = check_subtree($tree->{$first}, $mode, $sev, @rest);
}
# if we didn't get a severity already, check for matching globs
unless ($sev) {
# check each glob at this directory level
for my $chunk (grep { index($_, "*") != -1 } keys %{$tree}) {
# does it match the rest of our path?
if ($path =~ /^$chunk$/) {
# if we've got a ranking, check if it's higher than
# current one, if any
if ($tree->{$chunk}->{SD_RANK}) {
for my $m (split(//, $mode)) {
if ((!defined $sev)
|| $tree->{$chunk}->{SD_RANK}->{$m} > $sev)
{
$sev = $tree->{$chunk}->{SD_RANK}->{$m};
}
}
}
}
}
}
return $sev;
}
sub handle_file ($$) {
my ($self, $resource, $mode) = @_;
# strip off the initial / from the path we're checking
$resource = substr($resource, 1);
# break the path into directory-level chunks
my @pieces = split(/\//, $resource);
my $sev;
# if there's a exact match for this path in the db, use that instead of
# checking the globs
if ($self->{FILES}{$resource}) {
# check each piece of the passed mode against the db entry
for my $m (split(//, $mode)) {
if ((!defined $sev) || $self->{FILES}{$resource}{$m} > $sev) {
$sev = $self->{FILES}{$resource}{$m};
}
}
} else {
# descend into the regexp tree looking for matches
$sev = check_subtree($self->{REGEXPS}, $mode, $sev, @pieces);
}
return (defined $sev) ? $sev : $self->{DEFAULT_RANK};
}
sub rank ($;$) {
my ($self, $resource, $mode) = @_;
if (substr($resource, 0, 1) eq "/") {
return $self->handle_file($resource, $mode);
} elsif (substr($resource, 0, 3) eq "CAP") {
return $self->handle_capability($resource);
} else {
return "unexpected rank input: $resource\n";
}
}
sub convert_regexp ($) {
my ($input) = shift;
# we need to convert subdomain regexps to perl regexps
my $regexp = $input;
# escape + . [ and ] characters
$regexp =~ s/(\+|\.|\[|\])/\\$1/g;
# convert ** globs to match anything
$regexp =~ s/\*\*/.SDPROF_INTERNAL_GLOB/g;
# convert * globs to match anything at current path level
$regexp =~ s/\*/[^\/]SDPROF_INTERNAL_GLOB/g;
# convert {foo,baz} to (foo|baz)
$regexp =~ y/\{\}\,/\(\)\|/ if $regexp =~ /\{.*\,.*\}/;
# twiddle the escaped * chars back
$regexp =~ s/SDPROF_INTERNAL_GLOB/\*/g;
return $regexp;
}
1; # so the require or use succeeds

View file

@ -1,62 +0,0 @@
# ----------------------------------------------------------------------
# Copyright (c) 1999, 2004-2009 NOVELL (All rights reserved)
# Copyright (c) 2010-2011, 2014 Canonical Ltd.
#
# 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 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, contact Novell, Inc.
# ----------------------------------------------------------------------
# NOTE: this Makefile has been adjusted from the original to assist in
# the installation of the Immunix perl modules, if they're still needed
# by users. Because the utilities conflict with their replacments, make
# install *will* *not* install them.
NAME = apparmor-utils
all:
COMMONDIR=../../common/
include $(COMMONDIR)/Make.rules
MODDIR = Immunix
PERLTOOLS = aa-genprof aa-logprof aa-autodep aa-audit aa-complain aa-enforce \
aa-unconfined aa-disable
MODULES = ${MODDIR}/AppArmor.pm ${MODDIR}/Repository.pm \
${MODDIR}/Config.pm ${MODDIR}/Severity.pm
all:
# need some better way of determining this
DESTDIR=/
BINDIR=${DESTDIR}/usr/sbin
CONFDIR=${DESTDIR}/etc/apparmor
VENDOR_PERL=$(shell perl -e 'use Config; print $$Config{"vendorlib"};')
PERLDIR=${DESTDIR}${VENDOR_PERL}/${MODDIR}
.PHONY: install
install:
install -d ${PERLDIR}
install -m 644 ${MODULES} ${PERLDIR}
.PHONY: clean
ifndef VERBOSE
.SILENT: clean
endif
clean: pod_clean
rm -f core core.* *.o *.s *.a *~
rm -rf staging/ build/
.PHONY: check
.SILENT: check
check:
for i in ${MODULES} ${PERLTOOLS} ; do \
perl -c $$i || exit 1; \
done

View file

@ -1,132 +0,0 @@
#!/usr/bin/perl
# ----------------------------------------------------------------------
# Copyright (c) 2005 Novell, Inc. All Rights Reserved.
# Copyright (c) 2011 Canonical, Ltd.
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, contact Novell, Inc.
#
# To contact Novell about this file by physical or electronic mail,
# you may find current contact information at www.novell.com.
# ----------------------------------------------------------------------
use strict;
use FindBin;
use Getopt::Long;
use Immunix::AppArmor;
use Data::Dumper;
use Locale::gettext;
use POSIX;
# initialize the local poo
setlocale(LC_MESSAGES, "");
textdomain("apparmor-utils");
$UI_Mode = "text";
# options variables
my $help = '';
GetOptions(
'dir|d=s' => \$profiledir,
'help|h' => \$help,
);
# tell 'em how to use it...
&usage && exit if $help;
# let's convert it to full path...
$profiledir = get_full_path($profiledir);
unless (-d $profiledir) {
UI_Important("Can't find AppArmor profiles in $profiledir.");
exit 1;
}
# what are we profiling?
my @profiling = @ARGV;
unless (@profiling) {
@profiling = (UI_GetString("Please enter the program to switch to audit mode: ", ""));
}
for my $profiling (@profiling) {
next unless $profiling;
my $fqdbin;
if (-e $profiling) {
$fqdbin = get_full_path($profiling);
chomp($fqdbin);
} else {
if ($profiling !~ /\//) {
opendir(DIR,$profiledir);
my @tmp_fqdbin = grep ( /$profiling/, readdir(DIR));
closedir(DIR);
if (scalar @tmp_fqdbin eq 1) {
$fqdbin = "$profiledir/$tmp_fqdbin[0]";
} else {
my $which = which($profiling);
if ($which) {
$fqdbin = get_full_path($which);
}
}
}
}
if (-e $fqdbin) {
my $filename;
if ($fqdbin =~ /^$profiledir\//) {
$filename = $fqdbin;
} else {
$filename = getprofilefilename($fqdbin);
}
# argh, skip directories
next unless -f $filename;
# skip rpm backup files
next if isSkippableFile($filename);
printf(gettext('Setting %s to audit mode.'), $fqdbin);
print "\n";
setprofileflags($filename, "audit");
my $cmd_info = qx(cat $filename | $parser -I$profiledir -r 2>&1 1>/dev/null);
if ($? != 0) {
UI_Info($cmd_info);
exit $?;
}
# if check_for_subdomain();
} else {
if ($profiling =~ /^[^\/]+$/) {
UI_Info(sprintf(gettext('Can\'t find %s in the system path list. If the name of the application is correct, please run \'which %s\' as a user with the correct PATH environment set up in order to find the fully-qualified path.'), $profiling, $profiling));
exit 1;
} else {
UI_Info(sprintf(gettext('%s does not exist, please double-check the path.'), $profiling));
exit 1;
}
}
}
exit 0;
sub usage {
UI_Info(sprintf(gettext("usage: \%s [ -d /path/to/profiles ] [ program to switch to audit mode ]"), $0));
exit 0;
}

View file

@ -1,122 +0,0 @@
#!/usr/bin/perl
# ----------------------------------------------------------------------
# Copyright (c) 2005 Novell, Inc. All Rights Reserved.
# Copyright (c) 2011 Canonical, Ltd.
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, contact Novell, Inc.
#
# To contact Novell about this file by physical or electronic mail,
# you may find current contact information at www.novell.com.
# ----------------------------------------------------------------------
use strict;
use FindBin;
use Getopt::Long;
use Immunix::AppArmor;
use Data::Dumper;
use Locale::gettext;
use POSIX;
# force $PATH to be sane
$ENV{PATH} = "/bin:/sbin:/usr/bin:/usr/sbin";
# initialize the local poo
setlocale(LC_MESSAGES, "");
textdomain("apparmor-utils");
$UI_Mode = "text";
# options variables
my $help = '';
my $force = undef;
GetOptions(
'force' => \$force,
'dir|d=s' => \$profiledir,
'help|h' => \$help,
);
# tell 'em how to use it...
&usage && exit if $help;
my $sd_mountpoint = check_for_subdomain();
# let's convert it to full path...
$profiledir = get_full_path($profiledir);
unless (-d $profiledir) {
UI_Important(sprintf(gettext('Can\'t find AppArmor profiles in %s.'), $profiledir));
exit 1;
}
# what are we profiling?
my @profiling = @ARGV;
unless (@profiling) {
@profiling = (UI_GetString(gettext("Please enter the program to create a profile for: "), ""));
}
for my $profiling (@profiling) {
next unless $profiling;
my $fqdbin;
if (-e $profiling) {
$fqdbin = get_full_path($profiling);
chomp($fqdbin);
} else {
if ($profiling !~ /\//) {
my $which = which($profiling);
if ($which) {
$fqdbin = get_full_path($which);
}
}
}
# make sure that the app they're requesting to profile is not marked as
# not allowed to have it's own profile
if ($qualifiers{$fqdbin}) {
unless ($qualifiers{$fqdbin} =~ /p/) {
UI_Info(sprintf(gettext('%s is currently marked as a program that should not have it\'s own profile. Usually, programs are marked this way if creating a profile for them is likely to break the rest of the system. If you know what you\'re doing and are certain you want to create a profile for this program, edit the corresponding entry in the [qualifiers] section in /etc/apparmor/logprof.conf.'), $fqdbin));
exit 1;
}
}
if (-e $fqdbin) {
if (-e getprofilefilename($fqdbin) && !$force) {
UI_Info(sprintf(gettext('Profile for %s already exists - skipping.'), $fqdbin));
} else {
autodep($fqdbin);
reload($fqdbin) if $sd_mountpoint;
}
} else {
if ($profiling =~ /^[^\/]+$/) {
UI_Info(sprintf(gettext('Can\'t find %s in the system path list. If the name of the application is correct, please run \'which %s\' as a user with the correct PATH environment set up in order to find the fully-qualified path.'), $profiling, $profiling));
exit 1;
} else {
UI_Info(sprintf(gettext('%s does not exist, please double-check the path.'), $profiling));
exit 1;
}
}
}
exit 0;
sub usage {
UI_Info("usage: $0 [ --force ] [ -d /path/to/profiles ]");
exit 0;
}

View file

@ -1,131 +0,0 @@
#!/usr/bin/perl
# ----------------------------------------------------------------------
# Copyright (c) 2005 Novell, Inc. All Rights Reserved.
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, contact Novell, Inc.
#
# To contact Novell about this file by physical or electronic mail,
# you may find current contact information at www.novell.com.
# ----------------------------------------------------------------------
use strict;
use FindBin;
use Getopt::Long;
use Immunix::AppArmor;
use Data::Dumper;
use Locale::gettext;
use POSIX;
# initialize the local poo
setlocale(LC_MESSAGES, "");
textdomain("apparmor-utils");
$UI_Mode = "text";
# options variables
my $help = '';
GetOptions(
'dir|d=s' => \$profiledir,
'help|h' => \$help,
);
# tell 'em how to use it...
&usage && exit if $help;
# let's convert it to full path...
$profiledir = get_full_path($profiledir);
unless (-d $profiledir) {
UI_Important("Can't find AppArmor profiles in $profiledir.");
exit 1;
}
# what are we profiling?
my @profiling = @ARGV;
unless (@profiling) {
@profiling = (UI_GetString(gettext("Please enter the program to switch to complain mode: "), ""));
}
for my $profiling (@profiling) {
next unless $profiling;
my $fqdbin;
if (-e $profiling) {
$fqdbin = get_full_path($profiling);
chomp($fqdbin);
} else {
if ($profiling !~ /\//) {
opendir(DIR,$profiledir);
my @tmp_fqdbin = grep ( /$profiling/, readdir(DIR));
closedir(DIR);
if (scalar @tmp_fqdbin eq 1) {
$fqdbin = "$profiledir/$tmp_fqdbin[0]";
} else {
my $which = which($profiling);
if ($which) {
$fqdbin = get_full_path($which);
}
}
}
}
if (-e $fqdbin) {
my $filename;
if ($fqdbin =~ /^$profiledir\//) {
$filename = $fqdbin;
} else {
$filename = getprofilefilename($fqdbin);
}
# argh, skip directories
next unless -f $filename;
# skip rpm backup files
next if isSkippableFile($filename);
printf(gettext('Setting %s to complain mode.'), $fqdbin);
print "\n";
setprofileflags($filename, "complain");
my $cmd_info = qx(cat $filename | $parser -I$profiledir -r 2>&1 1>/dev/null);
if ($? != 0) {
UI_Info($cmd_info);
exit $?;
}
# if check_for_subdomain();
} else {
if ($profiling =~ /^[^\/]+$/) {
UI_Info(sprintf(gettext('Can\'t find %s in the system path list. If the name of the application is correct, please run \'which %s\' as a user with the correct PATH environment set up in order to find the fully-qualified path.'), $profiling, $profiling));
exit 1;
} else {
UI_Info(sprintf(gettext('%s does not exist, please double-check the path.'), $profiling));
exit 1;
}
}
}
exit 0;
sub usage {
UI_Info(sprintf(gettext("usage: \%s [ -d /path/to/profiles ] [ program to switch to complain mode ]"), $0));
exit 0;
}

View file

@ -1,152 +0,0 @@
#!/usr/bin/perl
# ----------------------------------------------------------------------
# Copyright (c) 2005-2010 Novell, Inc. All Rights Reserved.
# Copyright (c) 2011 Canonical, Inc. All Rights Reserved.
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, contact Canonical, Inc.
#
# To contact Canonical about this file by physical or electronic mail,
# you may find current contact information at www.canonical.com.
# ----------------------------------------------------------------------
use strict;
use FindBin;
use Getopt::Long;
use Immunix::AppArmor;
use Data::Dumper;
use Locale::gettext;
use POSIX;
use File::Basename;
# initialize the local poo
setlocale(LC_MESSAGES, "");
textdomain("apparmor-utils");
$UI_Mode = "text";
# options variables
my $help = '';
GetOptions(
'dir|d=s' => \$profiledir,
'help|h' => \$help,
);
# tell 'em how to use it...
&usage && exit if $help;
# let's convert it to full path...
$profiledir = get_full_path($profiledir);
unless (-d $profiledir) {
UI_Important("Can't find AppArmor profiles in $profiledir.");
exit 1;
}
my $disabledir = "$profiledir/disable";
unless (-d $disabledir) {
UI_Important("Can't find AppArmor disable directory '$disabledir'.");
exit 1;
}
# what are we profiling?
my @profiling = @ARGV;
unless (@profiling) {
@profiling = (UI_GetString(gettext("Please enter the program whose profile should be disabled: "), ""));
}
for my $profiling (@profiling) {
next unless $profiling;
my $fqdbin;
if (-e $profiling) {
$fqdbin = get_full_path($profiling);
chomp($fqdbin);
} else {
if ($profiling !~ /\//) {
opendir(DIR,$profiledir);
my @tmp_fqdbin = grep ( /$profiling/, readdir(DIR));
closedir(DIR);
if (scalar @tmp_fqdbin eq 1) {
$fqdbin = "$profiledir/$tmp_fqdbin[0]";
} else {
my $which = which($profiling);
if ($which) {
$fqdbin = get_full_path($which);
}
}
}
}
if (-e $fqdbin) {
my $filename;
if ($fqdbin =~ /^$profiledir\//) {
$filename = $fqdbin;
} else {
$filename = getprofilefilename($fqdbin);
}
# argh, skip directories
next unless -f $filename;
# skip package manager backup files
next if isSkippableFile($filename);
my ($bname, $dname, $suffix) = File::Basename::fileparse($filename);
if ($bname eq "") {
UI_Info(sprintf(gettext('Could not find basename for %s.'), $filename));
exit 1;
}
printf(gettext('Disabling %s.'), $fqdbin);
print "\n";
my $link = "$disabledir/$bname";
if (! -e $link) {
if (symlink($filename, $link) != 1) {
UI_Info(sprintf(gettext('Could not create %s symlink.'), $link));
exit 1;
}
}
my $cmd_info = qx(cat $filename | $parser -I$profiledir -R 2>&1 1>/dev/null);
if ($? != 0) {
UI_Info($cmd_info);
exit $?;
}
# if check_for_subdomain();
} else {
if ($profiling =~ /^[^\/]+$/) {
UI_Info(sprintf(gettext('Can\'t find %s in the system path list. If the name of the application is correct, please run \'which %s\' as a user with the correct PATH environment set up in order to find the fully-qualified path.'), $profiling, $profiling));
exit 1;
} else {
UI_Info(sprintf(gettext('%s does not exist, please double-check the path.'), $profiling));
exit 1;
}
}
}
exit 0;
sub usage {
UI_Info(sprintf(gettext("usage: \%s [ -d /path/to/profiles ] [ program to have profile disabled ]"), $0));
exit 0;
}

View file

@ -1,142 +0,0 @@
#!/usr/bin/perl
# ----------------------------------------------------------------------
# Copyright (c) 2005 Novell, Inc. All Rights Reserved.
# Copyright (c) 2011 Canonical, Ltd.
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, contact Novell, Inc.
#
# To contact Novell about this file by physical or electronic mail,
# you may find current contact information at www.novell.com.
# ----------------------------------------------------------------------
use strict;
use FindBin;
use Getopt::Long;
use Immunix::AppArmor;
use Data::Dumper;
use Locale::gettext;
use POSIX;
# initialize the local poo
setlocale(LC_MESSAGES, "");
textdomain("apparmor-utils");
$UI_Mode = "text";
# options variables
my $help = '';
GetOptions(
'dir|d=s' => \$profiledir,
'help|h' => \$help,
);
# tell 'em how to use it...
&usage && exit if $help;
# let's convert it to full path...
$profiledir = get_full_path($profiledir);
unless (-d $profiledir) {
UI_Important("Can't find AppArmor profiles in $profiledir.");
exit 1;
}
# what are we profiling?
my @profiling = @ARGV;
unless (@profiling) {
@profiling = (UI_GetString(gettext("Please enter the program to switch to enforce mode: "), ""));
}
for my $profiling (@profiling) {
next unless $profiling;
my $fqdbin;
if (-e $profiling) {
$fqdbin = get_full_path($profiling);
chomp($fqdbin);
} else {
if ($profiling !~ /\//) {
opendir(DIR,$profiledir);
my @tmp_fqdbin = grep ( /$profiling/, readdir(DIR));
closedir(DIR);
if (scalar @tmp_fqdbin eq 1) {
$fqdbin = "$profiledir/$tmp_fqdbin[0]";
} else {
my $which = which($profiling);
if ($which) {
$fqdbin = get_full_path($which);
}
}
}
}
if (-e $fqdbin) {
my $filename;
if ($fqdbin =~ /^$profiledir\//) {
$filename = $fqdbin;
} else {
$filename = getprofilefilename($fqdbin);
}
# argh, skip directories
next unless -f $filename;
# skip rpm backup files
next if isSkippableFile($filename);
printf(gettext('Setting %s to enforce mode.'), $fqdbin);
print "\n";
setprofileflags($filename, "");
# remove symlink in $profiledir/force-complain as well
my $complainlink = $filename;
$complainlink =~ s/^$profiledir/$profiledir\/force-complain/;
-e $complainlink and unlink($complainlink);
# remove symlink in $profiledir/disable as well
my $disablelink = $filename;
$disablelink =~ s/^$profiledir/$profiledir\/disable/;
-e $disablelink and unlink($disablelink);
my $cmd_info = qx(cat $filename | $parser -I$profiledir -r 2>&1 1>/dev/null);
if ($? != 0) {
UI_Info($cmd_info);
exit $?;
}
# if check_for_subdomain();
} else {
if ($profiling =~ /^[^\/]+$/) {
UI_Info(sprintf(gettext('Can\'t find %s in the system path list. If the name of the application is correct, please run \'which %s\' as a user with the correct PATH environment set up in order to find the fully-qualified path.'), $profiling, $profiling));
exit 1;
} else {
UI_Info(sprintf(gettext('%s does not exist, please double-check the path.'), $profiling));
exit 1;
}
}
}
exit 0;
sub usage {
UI_Info(sprintf(gettext("usage: \%s [ -d /path/to/profiles ] [ program to switch to enforce mode ]"), $0));
exit 0;
}

View file

@ -1,940 +0,0 @@
#!/usr/bin/perl -w
# ----------------------------------------------------------------------
# Copyright (c) 2005 Novell, Inc. All Rights Reserved.
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, contact Novell, Inc.
#
# To contact Novell about this file by physical or electronic mail,
# you may find current contact information at www.novell.com.
# ----------------------------------------------------------------------
use strict;
use Data::Dumper;
use DBI;
use Fcntl;
use File::Temp qw(tempfile);
use Getopt::Long;
use POSIX 'setsid';
use Time::Local;
use File::Tail;
use Immunix::Severity;
require LibAppArmor;
##########################################################################
# locations
my $productname = "apparmor";
my $cfgdir = "/etc/$productname";
my $dbdir = "/var/log/$productname";
my $cfgfile = "$cfgdir/notify.cfg";
my $errlog = "$dbdir/event-dispatch.log";
my $logfile = "/var/log/audit/audit.log";
my $syslogfile = "/var/log/messages";
##########################################################################
# options variables
my $pidfile = '';
GetOptions('pidfile|p=s' => \$pidfile);
my $DEBUG = 0;
my $config;
my $verbose = { last_notify => 0 };
my $summary = { last_notify => 0 };
my $terse = { last_notify => 0 };
# we don't want to call str2time on every line and also batch up event dbs
# a month at a time, so we need to keep track of a few extra things
my $timestamp = 0;
my $lasttime = "";
my $counter = 0;
my $thismonth = 0;
my $nextmonth = 0;
# pop open a connection to the severity database
my $sevdb = new Immunix::Severity("$cfgdir/severity.db", -1);
my $REdate = '\w{3}\s+\d+\s+\d{2}:\d{2}:\d{2}';
my $last_inserted_time;
my $last_inserted_counter;
##########################################################################
# commit how often?
my $timeout = 5;
# keep track of when we commited last
my $last_flush_time = 0;
# keep track of some statistics
my $max = 0;
my $inserts = 0;
my $total = 0;
my @commit_buffer;
my @debug_buffer;
my @verbose_buffer;
my @summary_buffer;
my @terse_buffer;
my $date_module = "None";
my %templates = (
"path" => "(time,counter,type,op,profile,sdmode,mode_req,mode_deny,resource,prog,pid,severity) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)",
"link" => "(time,counter,type,op,profile,sdmode,resource,target,prog,pid,severity) VALUES(?,?,?,?,?,?,?,?,?,?,?)",
"chattr" => "(time,counter,type,op,profile,sdmode,resource,mode_req,mode_deny,prog,pid,severity) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)",
"capability" => "(time,counter,type,op,profile,sdmode,resource,prog,pid,severity) VALUES(?,?,?,?,?,?,?,?,?,?)",
"capable" => "(time,counter,type,op,prog,pid,profile) VALUES(?,?,?,?,?,?,?)",
"unknown_hat" => "(time,counter,type,op,profile,sdmode,resource,pid) VALUES(?,?,?,?,?,?,?,?)",
"fork" => "(time,counter,type,op,profile,sdmode,pid,resource) VALUES(?,?,?,?,?,?,?,?)",
"changing_profile" => "(time,counter,type,op,profile,sdmode,pid) VALUES(?,?,?,?,?,?,?)",
"profile_replacement" => "(time,counter,type,op,profile,sdmode,prog,pid,severity) VALUES(?,?,?,?,?,?,?,?,?)",
"net" => "(time,counter,type,op,net_family,net_socktype,net_proto,pid,profile) VALUES(?,?,?,?,?,?,?,?,?)",
"removed" => "(time,counter,type,op,severity) VALUES(?,?,?,?,?)",
"initialized" => "(time,counter,type,op,resource,severity) VALUES(?,?,?,?,?,?)",
"ctrl_var" => "(time,counter,type,op,resource,mode_req,mode_deny,severity) VALUES(?,?,?,?,?,?,?,?)",
"profile_load" => "(time,counter,type,op,resource,prog,pid) VALUES(?,?,?,?,?,?,?)",
);
##########################################################################
# generic functions
sub errlog ($) {
my $mesg = shift;
my $localtime = localtime(time);
print ERRLOG "[$localtime] $mesg\n";
}
sub readconfig () {
my $cfg = {};
# record when we read the config file
$cfg->{load_time} = time;
if (open(CFG, $cfgfile)) {
# yank in the values we need
while (<CFG>) {
$cfg->{$1} = $2 if /^(\S+)\s+(.+)\s*$/;
}
close(CFG);
}
return $cfg;
}
sub daemonize {
chdir '/' or die "Can't chdir to /: $!";
open STDIN, '/dev/null' or die "Can't read /dev/null: $!";
open STDOUT, '>/dev/null' or die "Can't write to /dev/null: $!";
defined(my $pid = fork) or die "Can't fork: $!";
exit if $pid;
setsid or die "Can't start a new session: $!";
open STDERR, '>&STDOUT' or die "Can't dup stdout: $!";
}
sub parsedate ($) {
my $time = shift;
my $timestamp = 0;
if ($date_module eq 'TimeDate') {
$timestamp = Date::Parse::str2time($time);
} elsif ($date_module eq 'DateManip') {
$timestamp = Date::Manip::UnixDate(Date::Manip::ParseDateString($time), '%s');
} else {
errlog "No date module found, exiing";
kill HUP => -$$;
}
return $timestamp;
}
##########################################################################
# database handling functions
sub connect_database ($) {
my $dbdir = shift;
my $dbh = DBI->connect("dbi:SQLite:dbname=$dbdir/events.db", "", "", {RaiseError=>1});
# we'll do the commits ourselves so performance doesn't suck
$dbh->{AutoCommit} = 0;
# bump up our cache size a little
$dbh->do("PRAGMA cache_size = 20000;");
# figure out if the tables already exist or not
my %existing_tables;
my $sth = $dbh->prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;");
$sth->execute;
while (my @row = $sth->fetchrow_array) {
$existing_tables{ $row[0] } = 1;
}
$sth->finish;
# create the info table and fill in the appropriate values for this db
unless ($existing_tables{info}) {
my $host = `hostname -f`;
chomp $host;
$dbh->do("CREATE TABLE info (name,value)");
$sth = $dbh->prepare("INSERT INTO info(name,value) VALUES(?,?)");
$sth->execute("version", "0.2");
$sth->execute("host", "$host");
}
# create the events table
unless ($existing_tables{events}) {
$dbh->do(
"CREATE TABLE events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
time INTEGER NOT NULL,
counter INTEGER NOT NULL,
op,
pid,
sdmode,
type,
mode_deny,
mode_req,
resource,
target,
profile,
prog,
name_alt,
attr,
parent,
active_hat,
net_family,
net_proto,
net_socktype,
severity INTEGER
)"
);
# set up the indexes we want
#my @indexes = qw(time type sdmode mode resource profile prog severity);
my @indexes = qw(time type op sdmode mode_req mode_deny resource profile prog severity);
for my $index (@indexes) {
$dbh->do("CREATE INDEX " . $index . "_idx ON events($index)");
}
}
# make sure our changes actually get saved
$dbh->commit || errlog "Error commiting changes: $!";
# mark the db as up to date as of now
$last_flush_time = time;
return $dbh;
}
##########################################################################
sub verbose_notify_handler {
my ($email, $file, $last, $level, $unknown) = @_;
$last = localtime($last);
my $now = time;
my $host = `hostname -f`;
chomp $host;
my $subj = "Verbose Security Report for $host.";
my $mesg = "The following security events occured since $last:\n\n";
my @events;
if (open(V, $file)) {
while (<V>) {
chomp;
if (/^(\d+) (\d+) (.+)$/) {
my ($timestamp, $counter, $logmsg) = ($1, $2, $3);
push @events, [ $timestamp, $counter ];
$mesg .= "$logmsg\n";
}
}
close(V);
if (@events) {
if ($DEBUG) {
my $count = scalar @events;
errlog "[$count events] sending verbose notification to $email.";
}
# actually send out the notification...
open(MAIL, "| sendmail -F 'AppArmor Security Notification' $email");
print MAIL "To: $email\n";
print MAIL "Subject: $subj\n\n";
print MAIL "$mesg\n";
print MAIL ".\n";
close(MAIL);
}
# delete the verbose notification logfile once we've processed it
unlink($file);
}
}
sub summary_notify_handler {
my ($email, $file, $last, $level, $unknown) = @_;
$last = localtime($last);
my $now = time;
my $host = `hostname -f`;
chomp $host;
my $subj = "Summary Security Report for $host.";
my $mesg = "The following security events occured since $last:\n\n";
my @events;
if (open(V, $file)) {
while (<V>) {
chomp;
if (/^(\d+) (\d+) (.+)$/) {
my ($timestamp, $counter, $logmsg) = ($1, $2, $3);
push @events, [ $timestamp, $counter ];
$mesg .= "$logmsg\n";
}
}
close(V);
if (@events) {
if ($DEBUG) {
my $count = scalar @events;
errlog "[$count events] sending summary notification to $email.";
}
# actually send out the notification...
open(MAIL, "| sendmail -F 'AppArmor Security Notification' $email");
print MAIL "To: $email\n";
print MAIL "Subject: $subj\n\n";
print MAIL "$mesg\n";
print MAIL ".\n";
close(MAIL);
}
# delete the verbose notification logfile once we've processed it
unlink($file);
}
}
sub terse_notify_handler {
my ($email, $file, $last, $level, $unknown) = @_;
$last = localtime($last);
my $now = time;
my $host = `hostname -f`;
chomp $host;
my @events;
my $count = 0;
if (open(V, $file)) {
while (<V>) {
chomp;
if (/^(\d+) (\d+) (.+)$/) {
my ($timestamp, $counter, $logmsg) = ($1, $2, $3);
push @events, [ $timestamp, $counter ];
$count++;
}
}
close(V);
if ($count) {
if ($DEBUG) {
errlog "[$count events] sending terse notification to $email.";
}
my $subj = "Security Report for $host.";
my $mesg = "$host has had $count security events since $last.";
# actually send out the notification...
open(MAIL, "| sendmail -F 'AppArmor Security Notification' $email");
print MAIL "To: $email\n";
print MAIL "Subject: $subj\n\n";
print MAIL "$mesg\n";
print MAIL ".\n";
close(MAIL);
}
# delete the terse notification logfile once we've processed it
unlink($file);
}
}
sub fork_into_background {
my ($name, $func, @args) = @_;
my $pid = fork;
if (not defined $pid) {
# something bad happened, just log it...
errlog "couldn't fork for \"$name\": $!"
} elsif ($pid == 0) {
# we're in the child process now...
# set our process name
$0 = $name;
# call our subroutine
my $ret = &$func(@args);
exit($ret);
}
return $pid;
}
##########################################################################
# Parse event record into key-value pairs
sub parseEvent($) {
my %ev = ();
my $msg = shift;
chomp($msg);
my $event = LibAppArmor::parse_record($msg);
# resource is an alternate term for 'name1' below
# mode is an alternate term for 'mode_deny' below
$ev{'time'} = LibAppArmor::aa_log_record::swig_epoch_get($event);
$ev{'op'} = LibAppArmor::aa_log_record::swig_operation_get($event);
$ev{'pid'} = LibAppArmor::aa_log_record::swig_pid_get($event);
$ev{'mode_deny'} = LibAppArmor::aa_log_record::swig_denied_mask_get($event);
$ev{'mode_req'} = LibAppArmor::aa_log_record::swig_requested_mask_get($event);
$ev{'profile'}= LibAppArmor::aa_log_record::swig_profile_get($event);
$ev{'prog'} = LibAppArmor::aa_log_record::swig_name_get($event);
$ev{'name2'} = LibAppArmor::aa_log_record::swig_name2_get($event);
$ev{'attr'} = LibAppArmor::aa_log_record::swig_attribute_get($event);
$ev{'parent'} = LibAppArmor::aa_log_record::swig_parent_get($event);
$ev{'magic_token'} = LibAppArmor::aa_log_record::swig_magic_token_get($event);
$ev{'resource'} = LibAppArmor::aa_log_record::swig_info_get($event);
$ev{'active_hat'} = LibAppArmor::aa_log_record::swig_active_hat_get($event);
$ev{'sdmode'} = LibAppArmor::aa_log_record::swig_event_get($event);
# NetDomain
if ( $ev{'op'} && $ev{'op'} =~ /socket/ ) {
next if $ev{'op'} =~ /create/;
$ev{'net_family'} = LibAppArmor::aa_log_record::swig_net_family_get($event);
$ev{'net_proto'} = LibAppArmor::aa_log_record::swig_net_protocol_get($event);
$ev{'net_socktype'} = LibAppArmor::aa_log_record::swig_net_sock_type_get($event);
}
LibAppArmor::free_record($event);
if ( ! $ev{'time'} ) { $ev{'time'} = time; }
# remove null responses
for (keys(%ev)) {
if ( ! $ev{$_} || $ev{$_} !~ /\w+/) {delete($ev{$_}); }
#errlog "EVENT: $_ is $ev{$_}";
}
if ( $ev{'sdmode'} ) {
#0 = invalid, 1 = error, 2 = AUDIT, 3 = ALLOW/PERMIT,
#4 = DENIED/REJECTED, 5 = HINT, 6 = STATUS/config change
if ( $ev{'sdmode'} == 2 ) { $ev{'sdmode'} = "AUDITING"; }
elsif ( $ev{'sdmode'} == 3 ) { $ev{'sdmode'} = "PERMITING"; }
elsif ( $ev{'sdmode'} == 4 ) { $ev{'sdmode'} = "REJECTING"; }
else { delete($ev{'sdmode'}); }
}
return \%ev;
}
sub process_event ($$) {
my $dbh = shift;
my $logmsg = shift;
my $sth;
my $severity = "";
my @eventList = ();
my $type = undef;
my $time = undef;
return unless $logmsg && $logmsg =~ /APPARMOR/;
my $ev = parseEvent($logmsg);
# skip logprof hints
if ( ! $ev->{'op'} || $ev->{'op'} eq 'clone') { return; }
$time = time; # XXX - do we want current time or $ev->{'time'}?
if ($time ne $lasttime) {
$counter = 0;
$timestamp = $time;
$lasttime = $time;
}
$counter++;
# some statistics...
$max = $counter if $counter > $max;
# if we already have events in the db, make sure we don't try to re-enter
# duplicates if we start up again and parse the same logfile over again
if ($last_inserted_time) {
return if $timestamp < $last_inserted_time;
if ($timestamp == $last_inserted_time) {
return if $counter <= $last_inserted_counter;
}
$last_inserted_time = undef;
}
if ( $ev->{'sdmode'} && $ev->{'sdmode'} eq "REJECTING") {
$severity = $sevdb->rank($ev->{'prog'}, $ev->{'mode_req'});
if ( ! $severity ) { $severity = "-1"; }
# we only do notification for enforce mode events
if ($config->{verbose_freq}) {
if ( ($severity >= $config->{verbose_level})
|| (($severity == -1) && $config->{verbose_unknown}))
{
push @verbose_buffer, [ $timestamp, $counter, $logmsg ];
}
}
if ($config->{summary_freq}) {
if ( ($severity >= $config->{summary_level})
|| (($severity == -1) && $config->{summary_unknown}))
{
push @summary_buffer, [ $timestamp, $counter, "path",
$ev->{'prog'}, $ev->{'mode_req'}, $ev->{'resource'} ];
}
}
if ($config->{terse_freq}) {
if ( ($severity >= $config->{terse_level})
|| (($severity == -1) && $config->{terse_unknown}))
{
push @terse_buffer, [ $timestamp, $counter, "dummy" ];
}
}
}
unless ( $ev->{'op'} ) {
my $errmsg = "ERROR: No operation found: ";
for my $k (sort keys(%$ev)) {
$errmsg .= "$k is $ev->{$k}, ";
}
errlog("$errmsg\n");
return;
}
# Format the message to match the db template
if ($ev->{'op'} eq 'link' ) {
$type = 'link';
push(@eventList, [$time,$counter,$type,$ev->{'profile'},$ev->{'sdmode'},
$ev->{'resource'},$ev->{'target'},$ev->{'prog'},$ev->{'pid'},$severity]);
} elsif ($ev->{'op'} eq 'attribute') {
$type = 'chattr';
push(@eventList, []);
push(@eventList, [$time,$counter,$type,$ev->{'op'},$ev->{'profile'},$ev->{'sdmode'},
$ev->{'resource'},$ev->{'mode_req'},$ev->{'mode_deny'},$ev->{'prog'},
$ev->{'pid'},$severity]);
} elsif ($ev->{'op'} eq 'capability') {
$type = 'capability';
push(@eventList, [$time,$counter,$type,$ev->{'op'},$ev->{'profile'},$ev->{'sdmode'},
$ev->{'resource'},$ev->{'prog'},$ev->{'pid'},$severity]);
} elsif ($ev->{'op'} eq 'capable') {
$type = 'capable';
push(@eventList, [$time,$counter,$type,$ev->{'op'},$ev->{'prog'},
$ev->{'profile'},$ev->{'pid'}]);
} elsif ($ev->{'op'} =~ /ontrol variable/ ) {
$type = 'ctrl_var';
push(@eventList, [$time,$counter,$type,$ev->{'op'},$ev->{'resource'},
$ev->{'mode_req'},$ev->{'mode_deny'},$severity]);
} elsif ($ev->{'op'} eq 'unknown_hat') {
$type = 'unknown_hat';
push(@eventList, [$time,$counter,$type,$ev->{'op'},$ev->{'profile'},$ev->{'sdmode'},
$ev->{'resource'},$ev->{'pid'},$severity]);
} elsif ($ev->{'op'} eq 'fork') {
$type = 'fork';
push(@eventList, [$time,$counter,$type,$ev->{'op'},$ev->{'profile'},$ev->{'sdmode'},
$ev->{'pid'},$ev->{'resource'}]);
} elsif ($ev->{'op'} eq 'changing_profile') {
$type = 'changing_profile';
push(@eventList, [$time,$counter,$type,$ev->{'op'},$ev->{'profile'},$ev->{'sdmode'},
$ev->{'pid'}]);
} elsif ($ev->{'op'} eq 'profile_load') {
$type = 'profile_load';
push(@eventList, [$time,$counter,$type,$ev->{'op'},$ev->{'resource'},
$ev->{'prog'},$ev->{'pid'}]);
} elsif ($ev->{'op'} eq 'profile_replace') {
$type = 'profile_replacement';
push(@eventList, [$time,$counter,$type,$ev->{'op'},$ev->{'profile'},$ev->{'sdmode'},
$ev->{'prog'},$ev->{'pid'},$severity]);
} elsif ($ev->{'op'} eq 'removed') {
$type = 'removed';
push(@eventList, [$time,$counter,$type,$ev->{'op'},$severity]);
} elsif ($ev->{'op'} eq 'initialized') {
$type = 'initialized';
push(@eventList, [$time,$counter,$type,$ev->{'op'},$ev->{'resource'},$severity]);
} elsif ( $ev->{'op'} =~ /socket/) {
$type = 'net';
push(@eventList, [$time,$counter,$type,$ev->{'op'},$ev->{'net_family'},
$ev->{'net_sock_type'},$ev->{'net_proto'},$ev->{'pid'},$ev->{'profile'}]);
} else {
$type = 'path';
if ( ! $ev->{'prog'} ) { $ev->{'prog'} = "NIL"; }
push(@eventList, [$time,$counter,$type,$ev->{'op'},$ev->{'profile'},
$ev->{'sdmode'},$ev->{'mode_req'},$ev->{'mode_deny'},$ev->{'resource'},
$ev->{'prog'},$ev->{'pid'},$severity]);
}
push(@commit_buffer, @eventList);
$inserts++;
}
sub dump_events {
my ($which, @events) = @_;
if ($DEBUG) {
my $count = scalar @events;
errlog "dumping $count events to $which db.";
}
if (open(F, ">>$dbdir/$which.db")) {
for my $event (@events) {
my @event = @$event;
print F "@event\n";
}
close(F);
} else {
errlog "can't write to $dbdir/$which.db: $!";
}
}
sub check_timers ($) {
my $dbh = shift;
# what time is it right... NOW
my $now = time;
# make sure we commit periodically
if (($inserts > 10000) || ($now >= ($last_flush_time + $timeout))) {
my $last_prepare = "";
my $sth;
for my $event (sort { $a->[0] cmp $b->[0] } @commit_buffer) {
my @event = @{$event};
#my $type = shift @event;
my $type = $event[2];
eval {
if ($type ne $last_prepare) {
$sth = $dbh->prepare("INSERT INTO events $templates{$type}");
$last_prepare = $type;
}
$sth->execute(@event);
};
if ($@) {
print ERRLOG "DBI Execution failed: $DBI::errstr\n";
}
#$sth->execute(@event);
}
$dbh->commit || errlog "Error commiting changes: $!";
# need to get the time again to include how much time it takes to
# actually write all this crap to the db
$now = time;
if ($DEBUG && $inserts) {
$total += $inserts;
my $delta = $now - $last_flush_time;
my $rate = int($inserts / $delta);
errlog "$rate/s $inserts in ${delta}s total=$total max=$max";
}
$last_flush_time = $now;
@commit_buffer = ();
$max = 0;
$inserts = 0;
if (@verbose_buffer) {
# if we've got verbose events, dump them
dump_events("verbose", @verbose_buffer);
# and clear out our buffer
@verbose_buffer = ();
}
if (@terse_buffer) {
# if we've got terse events, dump them
dump_events("terse", @terse_buffer);
# and clear out our buffer
@terse_buffer = ();
}
# bail out if we don't have notification configured
return unless -f $cfgfile;
# what time did we last read the config file?
my $load_time = $config->{load_time};
# check when the config file was last modified...
my $mtime = (stat($cfgfile))[9];
# if it's been changed since we last read the config file, we need to
# load the new settings
if ($load_time < $mtime) {
errlog "Reloading changed config file.";
$config = readconfig();
}
}
# bail out if we don't have notification configured
return unless -f $cfgfile;
if ($config->{terse_freq}) {
if (($terse->{last_notify} + $config->{terse_freq}) <= $now) {
if (-f "$dbdir/terse.db") {
$DEBUG && errlog "doing terse notification...";
# get a temporary filename...
my ($fh, $filename) = tempfile("terseXXXXXX", DIR => $dbdir);
# overwrite the temp file we just created...
rename("$dbdir/terse.db", $filename);
if ($DEBUG) {
errlog "terse file is $filename";
}
# do the actual notification in the background
fork_into_background("terse-notification",
\&terse_notify_handler,
$config->{terse_email},
$filename,
$terse->{last_notify},
$config->{terse_level},
$config->{terse_unknown});
# ...keep track of when we last sent out a notify
$terse->{last_notify} = $now;
}
}
}
if ($config->{summary_freq}) {
if (($summary->{last_notify} + $config->{summary_freq}) <= $now) {
if (-f "$dbdir/summary.db") {
$DEBUG && errlog "doing summary notification...";
# get a temporary filename...
my ($fh, $filename) = tempfile("summaryXXXXXX", DIR => $dbdir);
# overwrite the temp file we just created...
rename("$dbdir/summary.db", $filename);
# do the actual notification in the background
fork_into_background("summary-notification",
\&summary_notify_handler,
$config->{summary_email},
$filename,
$summary->{last_notify},
$config->{summary_level},
$config->{summary_unknown});
# ...keep track of when we last sent out a notify
$summary->{last_notify} = $now;
}
}
}
if ($config->{verbose_freq}) {
if (($verbose->{last_notify} + $config->{verbose_freq}) <= $now) {
if (-f "$dbdir/verbose.db") {
$DEBUG && errlog "doing verbose notification...";
# get a temporary filename...
my ($fh, $filename) = tempfile("verboseXXXXXX", DIR => $dbdir);
# overwrite the temp file we just created...
rename("$dbdir/verbose.db", $filename);
if ($DEBUG) {
errlog "verbose file is $filename";
}
# do the actual notification in the background
fork_into_background("verbose-notification",
\&verbose_notify_handler,
$config->{verbose_email},
$filename,
$verbose->{last_notify},
$config->{verbose_level},
$config->{verbose_unknown});
# ...keep track of when we last sent out a notify
$verbose->{last_notify} = $now;
}
}
}
}
sub get_last_event {
my $dbh = shift;
my ($time, $counter);
# get the oldest timestamp...
my $sth = $dbh->prepare('SELECT MAX(time) FROM events');
$sth->execute;
my @row = $sth->fetchrow_array || (0);
$time = $row[0];
if ($time) {
# get the highest counter for this timestamp...
$sth = $dbh->prepare("SELECT MAX(counter) FROM events WHERE time = $time");
$sth->execute;
@row = $sth->fetchrow_array || (0);
$counter = $row[0];
}
return ($time, $counter);
}
##########################################################################
# start the real magic...
my $finished;
# make sure we exit if someone sends us the right signal
sub sig_handler {
my $signame = shift;
errlog("Caught signal '$signame'. Exiting...");
$finished = 1;
}
# set up our error log without buffering
open(ERRLOG, ">>$dbdir/event-dispatch.log");
my $oldfd = select(ERRLOG);
$| = 1;
select($oldfd);
$config = readconfig();
# fork off into the background. we need to do this before we connect to
# the db, otherwise, we'll get an ugly error about rolling back a
# connection that's being destroyed
daemonize;
# automagically reap child processes
$SIG{INT} = \&sig_handler;
$SIG{TERM} = \&sig_handler;
$SIG{CHLD} = 'IGNORE';
# Sigh, portable dates in perl sucks
eval "use Date::Parse";
if (!$@) {
$date_module = 'TimeDate';
} else {
eval "use Date::Manip";
if (!$@) {
$date_module = 'DateManip';
} else {
errlog "Unable to load Date module; use either TimeDate or Date::Manip";
$finished = 1;
}
}
# if they want us to write a pid, do it
if ($pidfile) {
if (open(PIDFILE, ">$pidfile")) {
print PIDFILE "$$\n";
close(PIDFILE);
}
}
my $dbh = connect_database($dbdir);
($last_inserted_time, $last_inserted_counter) = get_last_event($dbh);
my $auditlog = File::Tail->new(
name => $logfile,
debug => 1,
tail => -1,
interval => 1,
maxinterval => 5,
adjustafter => 20,
errmode => "return",
ignore_noexistant => 1
);
my $syslog = File::Tail->new(
name => $syslogfile,
debug => 1,
tail => -1,
interval => 1,
maxinterval => 5,
adjustafter => 20,
errmode => "return",
ignore_noexistant => 1
);
my $line = '';
# process complete lines from the buffer...
while (not $finished) {
my ($nfound, $timeleft, @pending) = File::Tail::select(undef, undef, undef, $timeout, ($auditlog, $syslog));
foreach (@pending) {
process_event($dbh, $_->read);
}
# see if we should flush pending entries to disk and/or do notification
check_timers($dbh);
}
# make sure we don't exit with any pending events not written to the db
$dbh->commit || errlog "Error commiting changes: $!";
$dbh->disconnect || errlog "Error disconnecting from db: $!";
# close our error/debugging log file
close(ERRLOG);
unlink($pidfile) if $pidfile;
exit 0;

View file

@ -1,216 +0,0 @@
#!/usr/bin/perl
# ----------------------------------------------------------------------
# Copyright (c) 2005 Novell, Inc. All Rights Reserved.
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, contact Novell, Inc.
#
# To contact Novell about this file by physical or electronic mail,
# you may find current contact information at www.novell.com.
# ----------------------------------------------------------------------
use strict;
use Getopt::Long;
use Immunix::AppArmor;
use Data::Dumper;
use Locale::gettext;
use POSIX;
sub sysctl_read($) {
my $path = shift;
my $value = undef;
if (open(SYSCTL, "<$path")) {
$value = int(<SYSCTL>);
}
close(SYSCTL);
return $value;
}
sub sysctl_write($$) {
my $path = shift;
my $value = shift;
return if (!defined($value));
if (open(SYSCTL, ">$path")) {
print SYSCTL $value;
close(SYSCTl);
}
}
# force $PATH to be sane
$ENV{PATH} = "/bin:/sbin:/usr/bin:/usr/sbin";
# initialize the local poo
setlocale(LC_MESSAGES, "");
textdomain("apparmor-utils");
# options variables
my $help = '';
GetOptions(
'file|f=s' => \$filename,
'dir|d=s' => \$profiledir,
'help|h' => \$help,
);
# tell 'em how to use it...
&usage && exit if $help;
my $sd_mountpoint = check_for_subdomain();
unless ($sd_mountpoint) {
fatal_error(gettext("AppArmor does not appear to be started. Please enable AppArmor and try again."));
}
# let's convert it to full path...
$profiledir = get_full_path($profiledir);
unless (-d $profiledir) {
fatal_error "Can't find AppArmor profiles in $profiledir.";
}
# what are we profiling?
my $profiling = shift;
unless ($profiling) {
$profiling = UI_GetString(gettext("Please enter the program to profile: "), "")
|| exit 0;
}
my $fqdbin;
if (-e $profiling) {
$fqdbin = get_full_path($profiling);
chomp($fqdbin);
} else {
if ($profiling !~ /\//) {
my $which = which($profiling);
if ($which) {
$fqdbin = get_full_path($which);
}
}
}
unless ($fqdbin && -e $fqdbin) {
if ($profiling =~ /^[^\/]+$/) {
fatal_error(sprintf(gettext('Can\'t find %s in the system path list. If the name of the application is correct, please run \'which %s\' in the other window in order to find the fully-qualified path.'), $profiling, $profiling));
} else {
fatal_error(sprintf(gettext('%s does not exist, please double-check the path.'), $profiling));
}
}
# make sure that the app they're requesting to profile is not marked as
# not allowed to have it's own profile
check_qualifiers($fqdbin);
# load all the include files
loadincludes();
my $profilefilename = getprofilefilename($fqdbin);
if (-e $profilefilename) {
$helpers{$fqdbin} = getprofileflags($profilefilename) || "enforce";
} else {
autodep($fqdbin);
$helpers{$fqdbin} = "enforce";
}
if ($helpers{$fqdbin} eq "enforce") {
complain($fqdbin);
reload($fqdbin);
}
# 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.
my $ratelimit_sysctl = "/proc/sys/kernel/printk_ratelimit";
my $ratelimit_saved = sysctl_read($ratelimit_sysctl);
END { sysctl_write($ratelimit_sysctl, $ratelimit_saved); }
sysctl_write($ratelimit_sysctl, 0);
UI_Info(gettext("\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"));
UI_Important(gettext("Please start the application to be profiled in \nanother window and exercise its functionality now.\n\nOnce completed, select the \"Scan\" button 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."));
my $syslog = 1;
my $logmark = "";
my $done_profiling = 0;
$syslog = 0 if (-e "/var/log/audit/audit.log");
while (not $done_profiling) {
if ($syslog) {
$logmark = `date | md5sum`;
chomp $logmark;
$logmark = $1 if $logmark =~ /^([0-9a-f]+)/;
system("$logger -p kern.warn 'GenProf: $logmark'");
} else {
$logmark = last_audit_entry_time();
}
eval {
my $q = {};
$q->{headers} = [ gettext("Profiling"), $fqdbin ];
$q->{functions} = [ "CMD_SCAN", "CMD_FINISHED" ];
$q->{default} = "CMD_SCAN";
my ($ans, $arg) = UI_PromptUser($q);
if ($ans eq "CMD_SCAN") {
my $lp_ret = do_logprof_pass($logmark);
$done_profiling = 1 if $lp_ret eq "FINISHED";
} else {
$done_profiling = 1;
}
};
if ($@) {
if ($@ =~ /FINISHING/) {
$done_profiling = 1;
} else {
die $@;
}
}
}
for my $p (sort keys %helpers) {
if ($helpers{$p} eq "enforce") {
enforce($p);
reload($p);
}
}
UI_Info(gettext("Reloaded AppArmor profiles in enforce mode."));
UI_Info(gettext("\nPlease consider contributing your new profile! See\nthe following wiki page for more information:\nhttps://gitlab.com/apparmor/apparmor/wikis/Profiles\n"));
UI_Info(sprintf(gettext('Finished generating profile for %s.'), $fqdbin));
exit 0;
sub usage {
UI_Info(sprintf(gettext("usage: \%s [ -d /path/to/profiles ] [ -f /path/to/logfile ] [ program to profile ]"), $0));
exit 0;
}
sub last_audit_entry_time {
local $_ = `tail -1 /var/log/audit/audit.log`;
my $logmark;
if (/^*msg\=audit\((\d+\.\d+\:\d+).*\).*$/) {
$logmark = $1;
} else {
$logmark = "";
}
return $logmark;
}

View file

@ -1,72 +0,0 @@
#!/usr/bin/perl
# ----------------------------------------------------------------------
# Copyright (c) 2005 Novell, Inc. All Rights Reserved.
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, contact Novell, Inc.
#
# To contact Novell about this file by physical or electronic mail,
# you may find current contact information at www.novell.com.
# ----------------------------------------------------------------------
use strict;
use Data::Dumper;
use Getopt::Long;
use Locale::gettext;
use POSIX;
use Immunix::AppArmor;
# force $PATH to be sane
$ENV{PATH} = "/bin:/sbin:/usr/bin:/usr/sbin";
# initialize the local poo
setlocale(LC_MESSAGES, "");
textdomain("apparmor-utils");
setup_yast();
# options variables
my $help = '';
my $logmark;
GetOptions(
'file|f=s' => \$filename,
'dir|d=s' => \$profiledir,
'logmark|m=s' => \$logmark,
'help|h' => \$help,
);
# tell 'em how to use it...
&usage && exit if $help;
# let's convert it to full path...
$profiledir = get_full_path($profiledir);
unless (-d $profiledir) {
fatal_error "Can't find AppArmor profiles in $profiledir.";
}
# load all the include files
loadincludes();
do_logprof_pass($logmark);
shutdown_yast();
exit 0;
sub usage {
UI_Info(sprintf(gettext("usage: \%s [ -d /path/to/profiles ] [ -f /path/to/logfile ] [ -m \"mark in log to start processing after\""), $0));
exit 0;
}

View file

@ -1,698 +0,0 @@
#!/usr/bin/perl
# ------------------------------------------------------------------
#
# Copyright (C) 2009-2011 Canonical Ltd.
#
# 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 published by the Free Software Foundation.
#
# ------------------------------------------------------------------
#
# /etc/apparmor/notify.conf:
# # set to 'yes' to enable AppArmor DENIED notifications
# show_notifications="yes"
#
# # only people in use_group can run this script
# use_group="admin"
#
# $HOME/.apparmor/notify.conf can have:
# # set to 'yes' to enable AppArmor DENIED notifications
# show_notifications="yes"
#
use strict;
use warnings;
no warnings qw( once );
require LibAppArmor;
require POSIX;
require Time::Local;
require File::Basename;
use Getopt::Long;
my %prefs;
my $conf = "/etc/apparmor/notify.conf";
my $user_conf = "";
my $notify_exe = "/usr/bin/notify-send";
my $notify_home = "";
my $notify_display = "";
my $last_exe = "/usr/bin/last";
my $ps_exe = "/bin/ps";
my $url = "https://wiki.ubuntu.com/DebuggingApparmor";
my $nobody_user = "nobody";
my $nobody_group = "nogroup";
sub readconf;
sub parse_message;
sub format_message;
sub format_stats;
sub kill_running_daemons;
sub do_notify;
sub show_since;
sub do_last;
sub do_show_messages;
sub _error;
sub _warn;
sub _debug;
sub exitscript;
sub usage;
#
# Main script
#
# Clean environment
$ENV{PATH} = "/bin:/usr/bin";
$ENV{SHELL} = "/bin/sh";
defined($ENV{IFS}) and $ENV{IFS} = ' \t\n';
my $prog = File::Basename::basename($0);
if ($prog !~ /^[a-zA-Z0-9_\-]+$/) {
print STDERR "ERROR: bad programe name '$prog'\n";
exitscript(1);
}
$> == $< or die "Cannot be suid\n";
$) == $( or die "Cannot be sgid\n";
my $login;
our $orig_euid = $>;
my $opt_d = '';
my $opt_display = '';
my $opt_h = '';
my $opt_l = '';
my $opt_p = '';
my $opt_v = '';
my $opt_f = '';
my $opt_s = 0;
my $opt_u = '';
my $opt_w = 0;
GetOptions(
'debug|d' => \$opt_d,
'display=s' => \$opt_display,
'help|h' => \$opt_h,
'since-last|l' => \$opt_l,
'poll|p' => \$opt_p,
'verbose|v' => \$opt_v,
'file|f=s' => \$opt_f,
'since-days|s=n' => \$opt_s,
'user|u=s' => \$opt_u,
'wait|w=n' => \$opt_w,
);
if ($opt_h) {
usage;
exitscript(0);
}
# monitor file specified with -f, else use audit.log if auditd is running,
# otherwise kern.log
our $logfile = "/var/log/kern.log";
if ($opt_f) {
-f $opt_f or die "'$opt_f' does not exist. Aborting\n";
$logfile = $opt_f;
} else {
-e "/var/run/auditd.pid" and $logfile = "/var/log/audit/audit.log";
}
-r $logfile or die "Cannot read '$logfile'\n";
our $logfile_inode = get_logfile_inode($logfile);
our $logfile_size = get_logfile_size($logfile);
open (LOGFILE, "<$logfile") or die "Could not open '$logfile'\n";
# Drop priviliges, if running as root
if ($< == 0) {
$login = "root";
if (defined($ENV{SUDO_UID}) and defined($ENV{SUDO_GID})) {
$) = "$ENV{SUDO_GID} $ENV{SUDO_GID}" or _error("Could not change egid");
$( = $ENV{SUDO_GID} or _error("Could not change gid");
$> = $ENV{SUDO_UID} or _error("Could not change euid");
defined($ENV{SUDO_USER}) and $login = $ENV{SUDO_USER};
} else {
my $drop_to = $nobody_user;
if ($opt_u) {
$drop_to = $opt_u;
}
# nobody/nogroup
my $nam = scalar(getgrnam($nobody_group));
$) = "$nam $nam" or _error("Could not change egid");
$( = $nam or _error("Could not change gid");
$> = scalar(getpwnam($drop_to)) or _error("Could not change euid to '$drop_to'");
}
} else {
$login = getlogin();
defined $login or $login = $ENV{'USER'};
}
if (-s $conf) {
readconf($conf);
if (defined($prefs{use_group})) {
my ($name, $passwd, $gid, $members) = getgrnam($prefs{use_group});
if (not defined($members) or not defined($login) or (not grep { $_ eq $login } split(/ /, $members) and $login ne "root")) {
_error("'$login' must be in '$prefs{use_group}' group. Aborting.\nAsk your admin to add you to this group or to change the group in\n$conf if you want to use aa-notify.");
}
}
}
# find user's notify.conf
if (-e "$ENV{HOME}/.apparmor/notify.conf" ) {
# use legacy path if the conf file is there
$user_conf = "$ENV{HOME}/.apparmor/notify.conf";
} elsif (defined $ENV{XDG_CONFIG_HOME}) {
# use XDG_CONFIG_HOME if it is defined
$user_conf = "$ENV{XDG_CONFIG_HOME}/apparmor/notify.conf";
} else {
# fallback to the default value of XDG_CONFIG_HOME
$user_conf = "$ENV{HOME}/.config/apparmor/notify.conf";
}
if ($opt_p) {
# notify-send is packaged in libnotify-bin on Debian/Ubuntu, libnotify-tools on openSUSE
-x "$notify_exe" or _error("Could not find '$notify_exe'. Please install it (package libnotify-bin or libnotify-tools). Aborting");
# we need correct values for $HOME and $DISPLAY environment variables,
# otherwise $notify_exe won't be able to connect to DBUS to display the
# message. Do this here to avoid excessive lookups.
$notify_home = (getpwuid $>)[7]; # homedir of the user
if ($opt_display ne '') {
$notify_display = $opt_display;
} elsif (defined($ENV{'DISPLAY'})) {
$notify_display = $ENV{'DISPLAY'};
}
if ($notify_display eq '') {
my $sudo_warn_msg = '';
if (defined($ENV{'SUDO_USER'})) {
$sudo_warn_msg = ' (or reset by sudo)';
}
_warn("Environment variable \$DISPLAY not set$sudo_warn_msg.");
_warn ('Desktop notifications will not work.');
if ($sudo_warn_msg ne '') {
_warn ('Use sudo aa-notify -p --display "$DISPLAY" to set the environment variable.');
} else {
_warn ('Use something like aa-notify -p --display :0 to set the environment variable.')
}
}
} elsif ($opt_l) {
-x "$last_exe" or _error("Could not find '$last_exe'. Aborting");
}
if ($opt_s and not $opt_l) {
$opt_s =~ /^[0-9]+$/ or _error("-s requires a number");
}
if ($opt_w) {
$opt_w =~ /^[0-9]+$/ or _error("-w requires a number");
}
if ($opt_p or $opt_l) {
if (-s $user_conf) {
readconf($user_conf);
}
if (defined($prefs{show_notifications}) and $prefs{show_notifications} ne "yes") {
_debug("'show_notifications' is disabled. Exiting");
exitscript(0);
}
}
my $now = time();
if ($opt_p) {
do_notify();
} elsif ($opt_l) {
do_last();
} elsif ($opt_s and not $opt_p) {
do_show_messages($opt_s);
} else {
usage;
exitscript(1);
}
exitscript(0);
#
# Subroutines
#
sub readconf {
my $cfg = $_[0];
-r $cfg or die "'$cfg' does not exist\n";
open (CFG, "<$cfg") or die "Could not open '$cfg'\n";
while (<CFG>) {
chomp;
s/#.*//; # no comments
s/^\s+//; # no leading white
s/\s+$//; # no trailing white
next unless length; # anything left?
my ($var, $value) = split(/\s*=\s*/, $_, 2);
if ($var eq "show_notifications" or $var eq "use_group" or $var eq "message_body" or $var eq "message_title" or $var eq "message_footer") {
$value =~ s/^"(.*)"$/$1/g;
$prefs{$var} = $value;
}
}
close(CFG);
}
sub parse_message {
my @params = @_;
my $msg = $params[0];
chomp($msg);
#_debug("processing: $msg");
my ($test) = LibAppArmorc::parse_record($msg);
# Don't show logs before certain date
my $date = LibAppArmor::aa_log_record::swig_epoch_get($test);
my $since = 0;
if (defined($date) and $#params > 0 and $params[1] =~ /^[0-9]+$/) {
$since = int($params[1]);
int($date) >= $since or goto err;
}
# ignore all but status and denied messages
my $type = LibAppArmor::aa_log_record::swig_event_get($test);
if ($type != $LibAppArmor::AA_RECORD_DENIED and $type != $LibAppArmor::AA_RECORD_ALLOWED) {
goto err;
}
my $profile = LibAppArmor::aa_log_record::swig_profile_get($test);
my $operation = LibAppArmor::aa_log_record::swig_operation_get($test);
my $name = LibAppArmor::aa_log_record::swig_name_get($test);
my $denied = LibAppArmor::aa_log_record::swig_denied_mask_get($test);
my $family = LibAppArmor::aa_log_record::swig_net_family_get($test);
my $sock_type = LibAppArmor::aa_log_record::swig_net_sock_type_get($test);
LibAppArmorc::free_record($test);
return ($profile, $operation, $name, $denied, $family, $sock_type, $date);
err:
LibAppArmorc::free_record($test);
return ();
}
sub format_message {
my ($profile, $operation, $name, $denied, $family, $sock_type, $date) = @_;
my $formatted = "";
if (defined($prefs{message_body})) {
$formatted .= $prefs{message_body};
} else {
defined($profile) and $formatted .= "Profile: $profile\n";
defined($operation) and $formatted .= "Operation: $operation\n";
defined($name) and $formatted .= "Name: $name\n";
defined($denied) and $formatted .= "Denied: $denied\n";
defined($family) and defined ($sock_type) and $formatted .= "Family: $family\nSocket type: $sock_type\n";
$formatted .= "Logfile: $logfile\n";
}
return $formatted;
}
sub format_stats {
my $num = $_[0];
my $time = $_[1];
if ($num > 0) {
print "AppArmor denial";
$num > 1 and print "s";
print ": $num (since " . scalar(localtime($time)) . ")\n";
$opt_v and print "For more information, please see: $url\n";
}
}
sub kill_running_daemons {
# Look for other daemon instances of this script and kill them. This
# can happen on logout and back in (in which case $notify_exe fails
# anyway). 'ps xw' should output something like:
# 9987 ? Ss 0:01 /usr/bin/perl ./bin/aa-notify -p
# 10170 ? Ss 0:00 /usr/bin/perl ./bin/aa-notify -p
open(PS,"$ps_exe xw|") or die "Unable to run '$ps_exe':$!\n";
while(<PS>) {
chomp;
/$prog -[ps]/ or next;
s/^\s+//;
my @line = split(/\s+/, $_);
if ($line[5] =~ /$prog$/ and ($line[6] eq "-p" or $line[6] eq "-s")) {
if ($line[0] != $$) {
_warn("killing old daemon '$line[0]'");
kill 15, ($line[0]);
}
}
}
close(PS);
}
sub send_message {
my $msg = $_[0];
my $pid = fork();
if ($pid == 0) { # child
# notify-send needs $< to be the unprivileged user
$< = $>;
$notify_home ne "" and $ENV{'HOME'} = $notify_home;
$notify_display ne "" and $ENV{'DISPLAY'} = $notify_display;
if (not defined($ENV{'DBUS_SESSION_BUS_ADDRESS'})) {
$ENV{'DBUS_SESSION_BUS_ADDRESS'} = "unix:path=/run/user/$>/bus";
}
# 'system' uses execvp() so no shell metacharacters here.
# $notify_exe is an absolute path so execvp won't search PATH.
system "$notify_exe", "-i", "gtk-dialog-warning", "-u", "normal", "--", "AppArmor Message", "$msg";
my $exit_code = $? >> 8;
exit($exit_code);
}
# parent
waitpid($pid, 0);
return $?;
}
sub do_notify {
my %seen;
my $seconds = 5;
our $time_to_die = 0;
print "Starting aa-notify\n";
kill_running_daemons();
# Daemonize, but not if in debug mode
if (not $opt_d) {
chdir('/') or die "Can't chdir to /: $!";
umask 0;
open STDIN, '/dev/null' or die "Can't read /dev/null: $!";
open STDOUT, '>/dev/null' or die "Can't write to /dev/null: $!";
#open STDERR, '>/dev/null' or die "Can't write to /dev/null: $!";
my $pid = fork();
exit if $pid;
die "Couldn't fork: $!" unless defined($pid);
POSIX::setsid() or die "Can't start a new session: $!";
}
sub signal_handler {
$time_to_die = 1;
}
$SIG{INT} = $SIG{TERM} = $SIG{HUP} = \&signal_handler;
$SIG{'PIPE'} = 'IGNORE';
if ($opt_w) {
sleep($opt_w);
}
my $count = 0;
my $footer = exists $prefs{message_footer} ? $prefs{message_footer} : "For more information, please see:\n$url";
my $first_run = 1;
my $since = $now;
if ($opt_s and int($opt_s) > 0) {
$since = $since - (int($opt_s) * 60 * 60 * 24);
}
for (my $i=0; $time_to_die == 0; $i++) {
if ($logfile_inode != get_logfile_inode($logfile)) {
_warn("$logfile changed inodes, reopening");
reopen_logfile();
} elsif (get_logfile_size($logfile) < $logfile_size) {
_warn("$logfile is smaller, reopening");
reopen_logfile();
}
while(my $msg = <LOGFILE>) {
my @attrib;
if ($first_run == 1) {
if ($since != $now) {
@attrib = parse_message($msg, $since);
}
} else {
@attrib = parse_message($msg);
}
$#attrib > 0 or next;
if ($first_run == 1) {
$count++;
next;
}
my ($profile, $operation, $name, $denied, $family, $sock_type, $date) = @attrib;
# Rate limit messages by creating a hash whose keys are:
# - for files: $profile|$name|$denied|
# - for everything else: $profile|$operation|$name|$denied|$family|$sock_type| (as available)
# The value for the key is a timestamp (epoch) and we won't show
# messages whose key has a timestamp from less than 5 seconds afo
my $k = "";
defined($profile) and $k .= "$profile|";
if (defined($name) and defined($denied)) {
$k .= "$name|$denied|"; # for file access, don't worry about operation
} else {
defined($operation) and $k .= "$operation|";
defined($name) and $k .= "$name|";
defined($denied) and $k .= "$denied|";
defined($family) and defined ($sock_type) and $k .= "$family|$sock_type|";
}
# don't display same message if seen in last 5 seconds
if (not defined($seen{$k})) {
$seen{$k} = time();
} else {
my $now = time();
$now - $seen{$k} < $seconds and next;
$seen{$k} = $now;
}
my $m = format_message(@attrib);
$m ne "" or next;
$m .= $footer;
my $rc = send_message($m);
if ($rc != 0) {
_warn("'$notify_exe' exited with error '$rc'");
$time_to_die = 1;
last;
}
}
# from seek() in Programming Perl
seek(LOGFILE, 0, 1);
sleep(1);
if ($first_run) {
if ($count > 0) {
my $m = "$logfile contains $count denied message";
$count > 1 and $m .= "s";
if ($opt_s) {
$m .= " in the last ";
if ($opt_s > 1) {
$m .= "$opt_s days";
} else {
$m .= "day";
}
}
$m .= ". ";
$m .= $footer;
send_message($m);
}
$first_run = 0;
}
# clean out the %seen database every 30 seconds
if ($i > 30) {
foreach my $k (keys %seen) {
my $now = time();
$now - $seen{$k} > $seconds and delete $seen{$k} and _debug("deleted $k");
}
$i = 0;
_debug("done purging");
foreach my $k (keys %seen) {
_debug("remaining key: $k: $seen{$k}");
}
}
}
print STDERR "Stopping aa-notify\n";
}
sub show_since {
my %msg_hash;
my %last_date;
my @msg_list;
my $count = 0;
while(my $msg = <LOGFILE>) {
my @attrib = parse_message($msg, $_[0]);
$#attrib > 0 or next;
my $m = format_message(@attrib);
$m ne "" or next;
my $date = $attrib[6];
if ($opt_v) {
if (exists($msg_hash{$m})) {
$msg_hash{$m}++;
defined($date) and $last_date{$m} = scalar(localtime($date));
} else {
$msg_hash{$m} = 1;
push(@msg_list, $m);
}
}
$count++;
}
if ($opt_v) {
foreach my $m (@msg_list) {
print "$m";
if ($msg_hash{$m} gt 1) {
print "($msg_hash{$m} found";
if (exists($last_date{$m})) {
print ", most recent from '$last_date{$m}'";
}
print ")\n";
}
print "\n";
}
}
return $count;
}
sub do_last {
open(LAST,"$last_exe -F -a $login|") or die "Unable to run $last_exe:$!\n";
my $time = 0;
while(my $line = <LAST>) {
_debug("Checking '$line'");
$line =~ /^$login/ or next;
$line !~ /^$login\s+pts.*\s+:[0-9]+\.[0-9]+$/ or next; # ignore xterm and friends
my @entry = split(/\s+/, $line);
my ($hour, $min, $sec) = (split(/:/, $entry[5]))[0,1,2];
$time = Time::Local::timelocal($sec, $min, $hour, $entry[4], $entry[3], $entry[6]);
last;
}
close(LAST);
$time > 0 or _error("Couldn't find last login");
format_stats(show_since($time), $time);
}
sub do_show_messages {
my $since = $now - (int($_[0]) * 60 * 60 * 24);
format_stats(show_since($since), $since);
}
sub _warn {
my $msg = $_[0];
print STDERR "aa-notify: WARN: $msg\n";
}
sub _error {
my $msg = $_[0];
print STDERR "aa-notify: ERROR: $msg\n";
exitscript(1);
}
sub _debug {
$opt_d or return;
my $msg = $_[0];
print STDERR "aa-notify: DEBUG: $msg\n";
}
sub exitscript {
my $rc = $_[0];
close(LOGFILE);
exit $rc;
}
sub usage {
my $s = <<'EOF';
USAGE: aa-notify [OPTIONS]
Display AppArmor notifications or messages for DENIED entries.
OPTIONS:
-p, --poll poll AppArmor logs and display notifications
--display $DISPLAY set the DISPLAY environment variable to $DISPLAY
(might be needed if sudo resets $DISPLAY)
-f FILE, --file=FILE search FILE for AppArmor messages
-l, --since-last display stats since last login
-s NUM, --since-days=NUM show stats for last NUM days (can be used alone
or with -p)
-v, --verbose show messages with stats
-h, --help display this help
-u USER, --user=USER user to drop privileges to when not using sudo
-w NUM, --wait=NUM wait NUM seconds before displaying
notifications (with -p)
EOF
print $s;
}
sub raise_privileges {
my $old_euid = -1;
if ($> != $<) {
_debug("raising privileges to '$orig_euid'");
$old_euid = $>;
$> = $orig_euid;
$> == $orig_euid or die "Could not raise privileges\n";
}
return $old_euid;
}
sub drop_privileges {
my $old_euid = $_[0];
# Just exit if we didn't raise privileges
$old_euid == -1 and return;
_debug("dropping privileges to '$old_euid'");
$> = $old_euid;
$> == $old_euid or die "Could not drop privileges\n";
}
sub reopen_logfile {
# reopen the logfile, temporarily switching back to starting euid for
# file permissions.
close(LOGFILE);
my $old_euid = raise_privileges();
$logfile_inode = get_logfile_inode($logfile);
$logfile_size = get_logfile_size($logfile);
open (LOGFILE, "<$logfile") or die "Could not open '$logfile'\n";
drop_privileges($old_euid);
}
sub get_logfile_size {
my $fn = $_[0];
my $size;
my $dir = File::Basename::dirname($fn);
# If we can't access the file, then raise privs. This can happen when
# using auditd and /var/log/audit/ is 700.
my $old_euid = -1;
if (! -x $dir) {
$old_euid = raise_privileges();
}
defined(($size = (stat($fn))[7])) or (sleep(10) and defined(($size = (stat($fn))[7])) or die "'$fn' disappeared. Aborting\n");
drop_privileges($old_euid);
return $size;
}
sub get_logfile_inode {
my $fn = $_[0];
my $inode;
my $dir = File::Basename::dirname($fn);
# If we can't access the file, then raise privs. This can happen when
# using auditd and /var/log/audit/ is 700.
my $old_euid = -1;
if (! -x $dir) {
$old_euid = raise_privileges();
}
defined(($inode = (stat($fn))[1])) or (sleep(10) and defined(($inode = (stat($fn))[1])) or die "'$fn' disappeared. Aborting\n");
drop_privileges($old_euid);
return $inode;
}
#
# end Subroutines
#

View file

@ -1,218 +0,0 @@
#!/usr/bin/perl -w
# ------------------------------------------------------------------
#
# Copyright (C) 2005-2006 Novell/SUSE
#
# 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 published by the Free Software Foundation.
#
# ------------------------------------------------------------------
use strict;
use Getopt::Long;
use Cwd 'abs_path';
my $confdir = "/etc/apparmor";
my $sd_mountpoint;
my $check_enabled = 0;
my $count_enforced = 0;
my $count_profiled = 0;
my $count_complain = 0;
my $verbose = 0;
my $help;
GetOptions(
'complaining' => \$count_complain,
'enabled' => \$check_enabled,
'enforced' => \$count_enforced,
'profiled' => \$count_profiled,
'verbose|v' => \$verbose,
'help|h' => \$help,
) or usage();
sub usage {
print "Usage: $0 [OPTIONS]\n";
print "Displays various information about the currently loaded AppArmor policy.\n";
print "OPTIONS (one only):\n";
print " --enabled returns error code if subdomain not enabled\n";
print " --profiled prints the number of loaded policies\n";
print " --enforced prints the number of loaded enforcing policies\n";
print " --complaining prints the number of loaded non-enforcing policies\n";
print " --verbose (default) displays multiple data points about loaded policy set\n";
print " --help this message\n";
exit;
}
$verbose = 1 if ($count_complain + $check_enabled + $count_enforced + $count_profiled == 0);
usage() if $help or ($count_complain + $check_enabled + $count_enforced + $count_profiled + $verbose > 1);
sub is_subdomain_loaded() {
return 1 if (-d "/sys/module/apparmor");
if(open(MODULES, "/proc/modules")) {
while(<MODULES>) {
return 1 if m/^(subdomain|apparmor)\s+/;
}
}
return 0;
}
sub find_subdomainfs() {
my $sd_mountpoint;
if(open(MOUNTS, "/proc/mounts")) {
while(<MOUNTS>) {
$sd_mountpoint = "$1/apparmor" if m/^\S+\s+(\S+)\s+securityfs\s/ && -e "$1/apparmor";
$sd_mountpoint = "$1/subdomain" if m/^\S+\s+(\S+)\s+securityfs\s/ && -e "$1/subdomain";
$sd_mountpoint = $1 if m/^\S+\s+(\S+)\s+subdomainfs\s/ && -e "$1";
}
close(MOUNTS);
}
return $sd_mountpoint;
}
sub get_profiles {
my $mountpoint = shift;
my %profiles = ();
if (open(PROFILES, "$mountpoint/profiles")) {
while(<PROFILES>) {
$profiles{$1} = $2 if m/^([^\(]+)\s+\((\w+)\)$/;
}
close(PROFILES);
}
return (%profiles);
}
sub get_processes {
my %profiles = @_;
my %processes = ();
if (opendir(PROC, "/proc")) {
my $file;
while (defined($file = readdir(PROC))) {
if ($file =~ m/^\d+/) {
if (open(CURRENT, "/proc/$file/attr/current")) {
while (<CURRENT>) {
if (m/^([^\(]+)\s+\((\w+)\)$/) {
$processes{$file}{'profile'} = $1;
$processes{$file}{'mode'} = $2;
} elsif (grep(abs_path("/proc/$file/exe") eq $_ , keys(%profiles))) {
# keep only unconfined processes that have a profile defined
$processes{$file}{'profile'} = abs_path("/proc/$file/exe");
$processes{$file}{'mode'} = 'unconfined';
}
}
close(CURRENT);
}
}
}
closedir(PROC);
}
return (%processes);
}
my $is_loaded = is_subdomain_loaded();
if (!$is_loaded) {
print STDERR "apparmor module is not loaded.\n" if $verbose;
exit 1;
}
print "apparmor module is loaded.\n" if $verbose;
$sd_mountpoint = find_subdomainfs();
if (!$sd_mountpoint) {
print STDERR "apparmor filesystem is not mounted.\n" if $verbose;
exit 3;
}
if (! -r "$sd_mountpoint/profiles") {
print STDERR "You do not have enough privilege to read the profile set.\n" if $verbose;
exit 4;
}
#print "subdomainfs is at $sd_mountpoint.\n" if $verbose;
# processes is a hash table :
# * keys : processes pid
# * values : hash containing information about the running process:
# * 'profile' : name of the profile applied to the running process
# * 'mode' : mode of the profile applied to the running process
my %processes = ();
my %enforced_processes = ();
my %complain_processes = ();
my %unconfined_processes = ();
# profiles is a hash table :
# * keys : profile name
# * value : profile mode
my %profiles;
my @enforced_profiles = ();
my @complain_profiles = ();
%profiles = get_profiles($sd_mountpoint);
@enforced_profiles = grep { $profiles{$_} eq 'enforce' } keys %profiles;
@complain_profiles = grep { $profiles{$_} eq 'complain' } keys %profiles;
# we consider the case where no profiles are loaded to be "disabled" as well
my $rc = (keys(%profiles) == 0) ? 2 : 0;
if ($check_enabled) {
exit $rc;
}
if ($count_profiled) {
print scalar(keys(%profiles)). "\n";
exit $rc;
}
if ($count_enforced) {
print $#enforced_profiles + 1 . "\n";
exit $rc;
}
if ($count_complain) {
print $#complain_profiles + 1 . "\n";
exit $rc;
}
if ($verbose) {
print keys(%profiles) . " profiles are loaded.\n";
print $#enforced_profiles + 1 . " profiles are in enforce mode.\n";
for (sort(@enforced_profiles)) {
print " " . $_ . "\n";
}
print $#complain_profiles + 1 . " profiles are in complain mode.\n";
for (sort(@complain_profiles)) {
print " " . $_ . "\n";
}
}
%processes = get_processes(%profiles);
if ($verbose) {
for (keys(%processes)) {
$enforced_processes{$_} = $processes{$_} if $processes{$_}{'mode'} eq 'enforce';
$complain_processes{$_} = $processes{$_} if $processes{$_}{'mode'} eq 'complain';
# some early code uses unconfined instead of unconfined.
$unconfined_processes{$_} = $processes{$_} if $processes{$_}{'mode'} =~ /uncon(fi|strai)ned/;
}
print keys(%processes) . " processes have profiles defined.\n";
print keys(%enforced_processes) . " processes are in enforce mode :\n";
for (sort { $enforced_processes{$a}{'profile'} cmp $enforced_processes{$b}{'profile'} } keys(%enforced_processes)) {
print " " . $enforced_processes{$_}{'profile'} . " ($_) \n";
}
print keys(%complain_processes) . " processes are in complain mode.\n";
for (sort { $complain_processes{$a}{'profile'} cmp $complain_processes{$b}{'profile'} } keys(%complain_processes)) {
print " " . $complain_processes{$_}{'profile'} . " ($_) \n";
}
print keys(%unconfined_processes) . " processes are unconfined but have a profile defined.\n";
for (sort { $unconfined_processes{$a}{'profile'} cmp $unconfined_processes{$b}{'profile'} } keys(%unconfined_processes)) {
print " " . $unconfined_processes{$_}{'profile'} . " ($_) \n";
}
}
exit $rc;

View file

@ -1,113 +0,0 @@
#!/usr/bin/perl -w
# ----------------------------------------------------------------------
# Copyright (c) 2005 Novell, Inc. All Rights Reserved.
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, contact Novell, Inc.
#
# To contact Novell about this file by physical or electronic mail,
# you may find current contact information at www.novell.com.
# ----------------------------------------------------------------------
#
# unconfined -
# audit local system for processes listening on network connections
# that are not currently running with a profile.
use strict;
use Getopt::Long;
use Immunix::AppArmor;
use Locale::gettext;
use POSIX;
setlocale(LC_MESSAGES, "");
textdomain("apparmor-utils");
# options variables
my $paranoid = '';
my $help = '';
GetOptions(
'paranoid' => \$paranoid,
'help|h' => \$help,
);
# tell 'em how to use it...
&usage && exit if $help;
sub usage {
printf(gettext("Usage: %s [ --paranoid ]\n"), $0);
exit 0;
}
my $subdomainfs = check_for_subdomain();
die gettext("AppArmor does not appear to be started. Please enable AppArmor and try again.") . "\n"
unless $subdomainfs;
my @pids;
if ($paranoid) {
opendir(PROC, "/proc") or die gettext("Can't read /proc\n");
@pids = grep { /^\d+$/ } readdir(PROC);
closedir(PROC);
} else {
if (open(NETSTAT, "LANG=C /bin/netstat -nlp |")) {
while (<NETSTAT>) {
chomp;
push @pids, $5
if /^(tcp|udp)\s+\d+\s+\d+\s+\S+\:(\d+)\s+\S+\:(\*|\d+)\s+(LISTEN|\s+)\s+(\d+)\/(\S+)/;
}
close(NETSTAT);
}
}
for my $pid (sort { $a <=> $b } @pids) {
my $prog = readlink "/proc/$pid/exe" or next;
my $attr;
if (open(CURRENT, "/proc/$pid/attr/current")) {
while (<CURRENT>) {
chomp;
$attr = $_ if (/^\// || /^null/);
}
close(CURRENT);
}
my $cmdline = `cat /proc/$pid/cmdline`;
my $pname = (split(/\0/, $cmdline))[0];
if ($pname =~ /\// && !($pname eq $prog)) {
$pname = "($pname) ";
} else {
$pname = "";
}
if (not $attr) {
if ($prog =~ m/^(\/usr\/bin\/python|\/usr\/bin\/perl|\/bin\/bash)$/) {
#my $scriptname = (split(/\0/, `cat /proc/$pid/cmdline`))[1];
$cmdline =~ s/\0/ /g;
$cmdline =~ s/\s+$//;
chomp $cmdline;
print "$pid $prog ($cmdline) " . gettext("not confined\n");
} else {
print "$pid $prog $pname" . gettext("not confined\n");
}
} else {
if ($prog =~ m/^(\/usr\/bin\/python|\/usr\/bin\/perl|\/bin\/bash)$/) {
#my $scriptname = (split(/\0/, `cat /proc/$pid/cmdline`))[1];
$cmdline =~ s/\0/ /g;
$cmdline =~ s/\s+$//;
chomp $cmdline;
print "$pid $prog ($cmdline) " . gettext("confined by") . " '$attr'\n";
} else {
print "$pid $prog $pname" . gettext("confined by") . " '$attr'\n";
}
}
}

View file

@ -1,201 +0,0 @@
#!/usr/bin/perl -wi
# automatically repair apparmor profiles that have had their supporting
# infrastructure refactored out from underneath them
# note -i in shebang line -- this program will modify in-place
# profiles or #include chunks specified on the command line without
# backups. Please make some yourself and inspect the changes made by
# this tool to ensure they look correct.
# It'll try to fix up #include files (supplied by SUSE/Immunix) that have
# moved; it will also inspect many #include files that exist solely
# for netdomain rule separation, and either remove the #include line
# from profiles/includes or suck in the contents of the specific file,
# depending if there was any non-netdomain content.
# If you haven't modified any of the files listed in the @useless array,
# you probably don't have to concern yourself with the complicated part
# of the previous paragraph. If you did modify any of those files, this
# tool will inspect those for changes, try to update any lines in those
# files for correctness, and insert those lines directly into the
# referencing profiles.
our %count_cache;
# count the number of 'interesting' lines in the file
sub numlines ($) {
my $name = $_[0];
return $count_cache{$name} if $count_cache{$name};
open FH, $name or return 1; # can't tell -> not empty
my $linecount=0;
while(<FH>) {
if (m/^[^#]*#include/) {
$linecount++;
} elsif (m/^\s*#/) {
# just a comment, skip it
} elsif (m/\s*tcp_/) {
# netdomain rules are unenforced, skip it
} elsif (m/\s*udp_/) {
# netdomain rules are unenforced, skip it
} elsif (m/\S+/) {
$linecount++;
}
}
close FH;
$count_cache{$name} = $linecount;
return $linecount;
}
# given a single line from a profile, perform some search/replace
# operations to reflect new locations for old files.
#
# change #include lines that reference files in the @useless array:
# don't print the #include any more, and either suck in the contents of
# the referenced file (calling itself recursively to fix up _those_
# files) or just leave well enough alone, if the file had no
# 'interesting' lines as defined above.
%transforms = (
# renamed around SuSE 9.3
"abstractions/kde3" => "abstractions/kde",
"abstractions/user-GTK" => "abstractions/gnome",
"abstractions/user-Xauthority" => "abstractions/X",
# user-custom -> program-chunks around SHASS 1.1, but these changed dirs
"user-custom/fonts" => "abstractions/fonts",
"user-custom/kde3" => "abstractions/kde",
"user-custom/user-GTK" => "abstractions/gnome",
"user-custom/user-mail" => "abstractions/user-mail",
"user-custom/user-manpages" => "abstractions/user-manpages",
"user-custom/user-Xauthority" => "abstractions/X",
"user-custom/user-tmp" => "abstractions/user-tmp",
# try to forget the -files
"program-chunks/base-files" => "abstractions/base",
"program-chunks/nameservice-files" => "abstractions/nameservice",
"immunix-standard/base-files" => "abstractions/base",
"immunix-standard/nameservice-files" => "abstractions/nameservice",
# immunix-standard -> program-chunks
"immunix-standard/postfix-bounce" => "program-chunks/postfix-bounce",
"immunix-standard/postfix-cleanup" => "program-chunks/postfix-cleanup",
"immunix-standard/postfix-common" => "program-chunks/postfix-common",
"immunix-standard/postfix-flush" => "program-chunks/postfix-flush",
"immunix-standard/postfix-local" => "program-chunks/postfix-local",
"immunix-standard/postfix-master" => "program-chunks/postfix-master",
"immunix-standard/postfix-nqmgr" => "program-chunks/postfix-nqmgr",
"immunix-standard/postfix-pickup" => "program-chunks/postfix-pickup",
"immunix-standard/postfix-proxymap" => "program-chunks/postfix-proxymap",
"immunix-standard/postfix-qmgr" => "program-chunks/postfix-qmgr",
"immunix-standard/postfix-showq" => "program-chunks/postfix-showq",
"immunix-standard/postfix-smtp" => "program-chunks/postfix-smtp",
"immunix-standard/postfix-smtpd" => "program-chunks/postfix-smtpd",
"immunix-standard/postfix-trivial-rewrite" => "program-chunks/postfix-trivial-rewrite",
"immunix-standard/apache-default-uri" => "program-chunks/apache-default-uri",
"immunix-standard/at" => "program-chunks/at",
);
# chunks that immunix tools never populated -- lets remove the ones that
# don't have any useful information
my @useless = qw{
program-chunks/base-nd
program-chunks/portmap-nd
program-chunks/postfix-local-nd
program-chunks/postfix-master-nd
program-chunks/postfix-proxymap-nd
program-chunks/postfix-smtpd-nd
program-chunks/postfix-smtp-nd
user-custom/base-nd
user-custom/portmap-nd
user-custom/postfix-local-nd
user-custom/postfix-master-nd
user-custom/postfix-proxymap-nd
user-custom/postfix-smtpd-nd
user-custom/postfix-smtp-nd
immunix-standard/base-nd
immunix-standard/portmap-nd
immunix-standard/postfix-local-nd
immunix-standard/postfix-master-nd
immunix-standard/postfix-proxymap-nd
immunix-standard/postfix-smtpd-nd
immunix-standard/postfix-smtp-nd
program-chunks/at
program-chunks/fam
program-chunks/httpd
program-chunks/identd
program-chunks/imapd
program-chunks/ipop2d
program-chunks/ipop3d
program-chunks/lpd
program-chunks/mutt
program-chunks/named
program-chunks/nmbd
program-chunks/ntalkd
program-chunks/ntpd
program-chunks/postgres
program-chunks/rpc.lockd
program-chunks/rpc.nfsd
program-chunks/rpc.statd
program-chunks/samba
program-chunks/sendmail.sendmail
program-chunks/shells
program-chunks/slocate
program-chunks/snmpd
program-chunks/spamc
program-chunks/sshd
program-chunks/swat
program-chunks/syslogd
program-chunks/talk
program-chunks/xfs
};
# create an alternation to speed up the regexp below
my $useless = join('|', @useless);
sub fixup ($) {
$line = $_[0];
$line =~ s/#include\s+<([^>]+)>/$i = (exists $transforms{$1}) ? $transforms{$1} : "$1"; "#include <$i>"/e;
if ($line =~ m/\s*#include\s+<($useless)>/) {
my $file = $1;
if (numlines("/etc/subdomain.d/$file") > 0) {
my $succ = open INC, "/etc/subdomain.d/$file";
if (not $succ) {
print STDERR "Error opening /etc/subdomain.d/$file\n";
} else {
while(my $included_line = <INC>) {
print fixup_loop($included_line);
}
close INC;
}
}
$line = ""; # this line has been handled by the file
}
return $line;
}
# call fixup on a single entry repeatedly -- this way, we can encode
# 'small' changes in the fixup routine when they are made, rather than
# encoding all possible starting points and which specific end point
# they should go to.
sub fixup_loop ($) {
my $line = $_[0];
my $saved;
do {
$saved = $line;
$line = fixup($saved);
} until ($line eq $saved);
return $line;
}
# main entry point; fix each line in every file in argv.
while(<>) {
print fixup_loop($_);
}