在审计或历史日志中记录 ssh REMOTE_USER

在审计或历史日志中记录 ssh REMOTE_USER

在我们的公司中,我们通常只有一个生产用户user,我们通过 ssh 密钥进行无密码登录来 ssh 到我们的服务器。

现在,有不少人都在这些服务器上工作,有时我们需要了解更改的原因以及更改者。为此,我们希望审计 bash 命令,但我们还需要保留原始远程用户 ID。解释如何定义${REMOTE_USER}变量,但是我们如何将其存储在每个命令的历史记录/审计日志中?

答案1

理想情况下,最好为每个人提供自己的 ssh 密钥对、自己的登录帐户,并用于sudo跟踪谁在做什么、在哪里做什么。如果您没有集中式身份验证和多台服务器,维护所有这些登录帐户可能会很麻烦(注意:请参阅ansible没有 LDAP 的更简单的方法),更不用说维护密码更改了。

我过去的做法是要求远程用户在其系统上导出一个名为 的变量LC_SSH_USER。sshd 配置可以通过设置接受此变量AcceptEnv LANG LC_*。登录时运行的脚本/etc/profile.d会“清理”变量和/或如果找不到变量则终止连接。此外,readonly变量上设置了 属性,因此无法轻易对变量进行无意更改。这样,无论远程用户登录到哪个帐户(www-datapassengeradmin),原始用户都会被记录。用户可以很容易地将变量设置为他们想要的任何值来绕过系统,但是可以制定 HR 策略来处理它。

示例脚本放置在/etc/profile.d/lc-ssh-user.sh它将记录 LC_SSH_USER 到/var/log/auth.log(在 Ubuntu 上):

# only allow letters, numbers and underscores in passed LC_SSH_USER variable
lc_ssh_user_sanitize()
{
   arg="{$1}"
   # first, strip underscores
   clean="${arg//_/}"

   # next, replace spaces with underscores
   clean="${clean// /_}"

   # now, clean out anything that's not alphanumeric or an underscore
   ret="${clean//[^a-zA-Z0-9_]/}"

   echo "${ret}"
}

# if SSH_CLIENT is not set, and LC_SSH_USER is not set, then this is a local login or a new shell opened by same user
if [ -z "${SSH_CLIENT}" ] && [ -z "${LC_SSH_USER}" ]; then
   export LC_SSH_USER=${USER}
else
   # otherwise, this is an ssh session - extract the connecting IP from env
   con=`echo "${SSH_CLIENT}" | cut -d'=' -f2 | cut -d' ' -f1`

   # export some variables needed for the user environment
   # when using "su --preserve-environment  userxxx --login" be sure to fixup needed variables
   export USER=`whoami`
   export LOGNAME=${USER}
   export HOME=$( getent passwd "$USER" | cut -d: -f6 )
   cd ${HOME}

   # user login without LC_SSH_USER set on their local machine
   if [ -z "${LC_SSH_USER}" ]; then
      echo "Error: LC_SSH_USER not set in connection from ${con} as user $USER" | logger -p auth.info
      #
      # connection could probably be terminated here to enforce the use of LC_SSH_USER
      #

      # since there is no LC_SSH_USER in the connection, just use whatever the user logged in as
      export LC_SSH_USER=${USER}
      echo "Notice: LC_SSH_USER set from login ${USER} from ${con}" | logger -p auth.info
   else
      # user has LC_SSH_USER set, so sanitize it (just in case) and log the sanitized version to syslog via logger
      u_sanitized=$(lc_ssh_user_sanitize "${LC_SSH_USER}")
      echo "Notice: LC_SSH_USER ${u_sanitized} login from ${con} as user $USER" | logger -p auth.info
   fi
fi

# always make LC_SSH_USER  readonly in the users environment
readonly LC_SSH_USER

更新:要使用的 git commit hook $LC_SSH_USER

#!/bin/sh
# To enable this hook drop this in ".git/hooks/pre-commit" (chmod 0755)
# It will create .commit_template if it does not exist
# add these lines to .git/config:
# [commit]
#   template = .commit_template
#
test -f .commit_template && exit 
echo "
Fix   : 
Issue : 
Author: $LC_SSH_USER
" > .commit_template

相关内容