#!/bin/sh
#
# script to update and rotate the AIDE database files and
# create a detached GPG signature to verify the database file
#
# written by Vincent Danen <vdanen-at-annvix.org>
#
# $Id: aideupdate 6662 2007-01-13 19:06:24Z vdanen $

TEXTDOMAIN=aidescripts

if command -v gpg2 >/dev/null 2>&1
then gpg=gpg2
else if command -v gpg >/dev/null 2>&1
then gpg=gpg
fi
fi
aide="/usr/sbin/aide"
fname="aide-`hostname`-`date +%Y%m%d-%H%M%S`"
host="`hostname`"

if [ ! -d /var/lib/aide ]; then
    printf $"FATAL: "$"The AIDE database directory %s does not exist!""\n\n" "/var/lib/aide"
    exit 1
fi

if [ ! -d /var/lib/aide/reports ]; then
    printf $"Creating %s to store reports""\n" "/var/lib/aide/reports"
    mkdir /var/lib/aide/reports && chmod 0700 /var/lib/aide/reports
fi

pushd /var/lib/aide >/dev/null

if [ -f aide.db ]; then
    if [ -f aide.db.sig ]; then
        # do an integrity check
	${gpg} --verify aide.db.sig
	if [ "$?" == "1" ]; then
	    printf "************************************************************\n"
	    printf $"GPG signature FAILED!  Your database has been tampered with!""\n"
	    printf "************************************************************\n"
	    exit 1
	fi
    else
        printf "**************************************************************\n"
        printf $"No GPG signature file found!  Your system may be compromised""\n"
        printf $"or incorrectly configured!  Please read man aideinit""\n"
        printf $"for more information on how to correctly configure AIDE!""\n"
        printf "**************************************************************\n"
        exit 1
    fi
    
    # this function signs the aide.db.new with gpg
    signfile() {
        unset gpgpass
        printf "\n"
        read -s -e -p $"Enter AIDE passphrase: " gpgpass
        printf "\n"
        echo ${gpgpass} | ${gpg} -u aide@${host} --passphrase-fd stdin --detach-sign aide.db.new
        if [ "$?" == "1" ]; then
            printf $"FATAL: "$"Error occurred when creating the signature file!""\n\n"
            exit 1
        fi
    }
    
    ${aide} --update \
		-B "report_url=file:/var/lib/aide/reports/${fname}.report" \
		-B "database_in=file:/var/lib/aide/aide.db" \
		-B "database_out=file:/var/lib/aide/aide.db.new"
    rm -f aide.db.new.sig
    signfile
    [[ ! -f aide.db.new.sig ]] && {
        printf $"No signature was created; bad passphrase? Try it again.""\n\n"
        signfile
    }
    [[ ! -f aide.db.new.sig ]] && {
        printf $"FATAL: "$"Signature was not created twice! Something is very wrong here.""\n\n"
        exit 1
    }
    printf $"Database has been successfully signed.""\n\n"
    mv aide.db.new aide.db
    mv aide.db.new.sig aide.db.sig
else
    printf $"The AIDE database does not exist, can't update!""\n\n"
    exit 1
fi

popd >/dev/null

exit 0
