Search code examples
linuxbashaudit

Differentiate between exit and session timeout


I have the following requierements:

  • produce audit log when bash session has been terminated by the user (exit)
  • produce audit log when bash session has timed out

Those audit logs must be different. I am playing around with the following script trap.sh:

export TMOUT=10

function handle-timeout {
    echo "Timeout"
}

function handle-exit {
    echo "Exit"
}

trap handle-exit EXIT

Now if I do:

valegon@precision ~ (master) $ bash
valegon@precision ~ (master) $ source trap.sh
valegon@precision ~ (master) $ exit
Exit

It works as expected. If instead, I wait for the timeout to happen:

valegon@precision ~ (master) $ bash
valegon@precision ~ (master) $ source trap.sh
valegon@precision ~ (master) $ timed out waiting for input: auto-logout
Exit

There are two problems here:

  1. the timeout is triggering EXIT, which I do not want
  2. I do not know how to trap the timeout specifically

How can I solve these open issues?


Solution

  • 2nd Attempt

    Based on feedback, previous solution using trap on EXIT does not work well. Alternative, based on using PROMPT_COMMAND seems to give better mileage.

    Basic Logic:

    • Capture command prompt time - start)
    • At 'exit' event, check if (now-start) > TMOUT
    • Normally, exit, CTRL/D, etc will finish in 1-2 seconds.
    #! /bin/bash
    function pre_cmd {
            START=$SECONDS
    }
    
    function log_exit {
        if [ "$((SECONDS-START-TMOUT))" -ge 0 ] ; then
           echo "TIMEOUT"
        else
           echo "Normal Exit"
        fi
    }
    
    TMOUT=15
    PROMPT_COMMAND=pre_cmd
    trap 'log_exit' EXIT