Differentiate between exit and session timeout

2020-04-07 23:05发布

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?

标签: linux bash audit
2条回答
放我归山
2楼-- · 2020-04-07 23:31

Same as Distinguish between user logout and session expired logout (SSH and web console)

I'm posting the same answer that I've posted there.

...

For normal sessions, which will have a login event, you can set a trap on the 'EXIT' event. This will cover explicit logout (CTRL/D, or exit), gettng killed by signal (NOT signal 9), and timeout. Look for bash 'trap' command. Those can be set at the loginn startup script (bashrc)

EDIT

It's possible to get indication of 'TIMEOUT' by checking '$?' in the TRAP handler. It will be 142 corresponding to ALRM signal (kill -l 142=ARLM). This is not explicitly document, but is consistent with the default signal handler for kill -ALRM.

function my_trap {
  local X=$1
  if [ "$X" = "$(kill -l ALRM)" ] ; then
     Log Timeout
  else
     Log Exit/EOF
  fi
}

trap 'my_trap $?' EXIT
查看更多
再贱就再见
3楼-- · 2020-04-07 23:41

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
查看更多
登录 后发表回答