Create a new article
Write your page title here:
We currently have 12 articles on NixSec. Type your article name above or click on one of the titles below and start writing!


    Nice bashrc options to secure history and auditting

    declare -rx HISTCONTROL=""                                  #does not ignore spaces or duplicates
    declare -rx HISTIGNORE=""                                   #does not ignore patterns
    declare -rx AUDIT_LOGINUSER="$(who -mu | awk '{print $1}')"
    declare -rx AUDIT_LOGINPID="$(who -mu | awk '{print $6}')"
    declare -rx AUDIT_USER="$USER"                              #defined by pam during su/sudo
    declare -rx AUDIT_PID="$$"
    declare -rx AUDIT_TTY="$(who -mu | awk '{print $2}')"
    declare -rx AUDIT_SSH="$([ -n "$SSH_CONNECTION" ] && echo "$SSH_CONNECTION" | awk '{print $1":"$2"->"$3":"$4}')"
    set +o functrace                                            #disable trap DEBUG inherited in functions, command substitutions or subshells, normally the default setting already
    shopt -s extglob                                            #enable extended pattern matching operators
    function audit_DEBUG() {
      if [ "$BASH_COMMAND" != "$PROMPT_COMMAND" ]               #avoid logging unexecuted commands after 'ctrl-c or 'empty+enter'
        local AUDIT_CMD="$(history 1)"                          #current history command
        if ! logger -p -t "$AUDIT_STR $PWD" "${AUDIT_CMD##*( )?(+([0-9])[^0-9])*( )}"
          echo error "$AUDIT_STR $PWD" "${AUDIT_CMD##*( )?(+([0-9])[^0-9])*( )}"
    function audit_EXIT() {
      local AUDIT_STATUS="$?"
      logger -p -t "$AUDIT_STR" "#=== bash session ended. ==="
      exit "$AUDIT_STATUS"
    declare -fr +t audit_DEBUG
    declare -fr +t audit_EXIT
    logger -p -t "$AUDIT_STR" "#=== New bash session started. ===" #audit the session openning
    #when a bash command is executed it launches first the audit_DEBUG(),
    #then the trap DEBUG is disabled to avoid a useless rerun of audit_DEBUG() during the execution of pipes-commands;
    #at the end, when the prompt is displayed, re-enable the trap DEBUG
    declare -rx PROMPT_COMMAND="trap 'audit_DEBUG; trap DEBUG' DEBUG"
    declare -rx BASH_COMMAND                                    #current command executed by user or a trap
    declare -rx SHELLOPT                                        #shell options, like functrace
    trap audit_EXIT EXIT