history命令:用于显示历史记录和执行过的指令命令。history命令读取历史命令文件中的目录到历史命令缓冲区和将历史命令缓冲区中的目录写入命令文件。该命令单独使用时,仅显示历史命令,在命令行中,可以使用符号!
执行指定序号的历史命令,下面为大家分享一下history命令使用方法。

1、命令历史记录中加时间
默认情况下如下图所示,没有命令执行时间,不利于审计分析。

通过设置export HISTTIMEFORMAT=’%F %T ‘,让历史记录中带上命令执行时间。
注意”%T”和后面的”’”之间有空格,不然查看历史记录的时候,时间和命令之间没有分割。
要一劳永逸,这个配置可以写在/etc/profile中,当然如果要对指定用户做配置,这个配置可以写在/home/$USER/.bash_profile中。
本文将以/etc/profile为例进行演示。

要使配置立即生效请执行source /etc/profile,我们再查看history记录,可以看到记录中带上了命令执行时间。

如果想要实现更细化的记录,比如登陆过系统的用户、IP地址、操作命令以及操作时间一一对应,可以通过在/etc/profile里面加入以下代码实现
export HISTTIMEFORMAT="\%F \%T`who \-u am i 2>/dev/null| awk '{print $NF}'|sed \-e 's/[()]//g'``whoami`
注意空格都是必须的。

修改/etc/profile并加载后,history记录如下,时间、IP、用户及执行的命令都一一对应。

通过以上配置,我们基本上可以满足日常的审计工作了,但了解系统的朋友应该很容易看出来,这种方法只是设置了环境变量,攻击者unset掉这个环境变量,或者直接删除命令历史,对于安全应急来说,这无疑是一个灾难。
针对这样的问题,我们应该如何应对,下面才是我们今天的重点,通过修改bash源码,让history记录通过syslog发送到远程logserver中,大大增加了攻击者对history记录完整性破坏的难度。
2、修改bash源码,支持syslog记录
首先下载bash源码,可以从gnu.org下载,这里不做详细说明了,系统需要安装gcc等编译环境。我们用bash4.4版本做演示。
修改源码:bashhist.c

修改源码config-top.h,取消/#define SYSLOG_HISTORY/这行的注释

编译安装,编译过程不做详细说明,本文中使用的编译参数为: ./configure –prefix=/usr/local/bash,安装成功后对应目录如下:

此时可以修改/etc/passwd中用户shell环境,也可以用编译好的文件直接替换原有的bash二进制文件,但最好对原文件做好备份。
替换时要注意两点:
1、一定要给可执行权限,默认是有的,不过有时候下载到windows系统后,再上传就没有可执行权限了,这里一定要确定,不然你会后悔的;
2、替换时原bash被占用,可以修改原用户的bash环境后再进行替换。
查看效果,我们发现history记录已经写到了/var/log/message中。

如果要写到远程logserver,需要配置syslog服务,具体配置这里不做详细讲解,大家自己研究,发送到远端logserver效果如下图所示。

通过以上手段,可以有效保证history记录的完整性,避免攻击者登录系统后,通过取消环境变量、删除history记录等方式抹掉操作行为,为安全审计、应急响应等提供了完整的原始数据。
以上就是良许教程网为各位朋友分享的Linux系统相关内容。想要了解更多Linux相关知识记得关注公众号“良许Linux”,或扫描下方二维码进行关注,更多干货等着你 !
