Enviando o histórico bash para o syslog

3

Versão Bash 4.N aparentemente tem a capacidade de escrever histórico de comandos para o syslog, mas não consigo encontrar informações sobre como configurar isso.

Eu li várias páginas que oferecem hacks usando o PROMPT_COMMAND e o trap e sei que há um patch disponível, mas isso deve ser desnecessário, já que agora está incorporado.

Eu sei que posso usar auditd para capturar comandos, mas gostaria de usar a combinação bash / syslog.

Alguém pode aconselhar, por favor?

    
por Graham Nicholls 19.07.2018 / 01:06

1 resposta

6

Essa abordagem parece ser o que você está procurando. Este artigo discute, intitulado: Melhorando as Capacidades Forenses do Bash .

Trecho:

While discussing with him about this topic, I realized that there are some ways to fine tune the history of commands to improve forensics investigations. In 2009, I also wrote a blog post about Bash which gave some ideas to send a Bash command history to a remote Syslog server. I checked my web logs and this blog post remains popular with more than 1000 visits for the last 30 days! Note that my blog post is outdated: Since the version 4.1, Bash supports Syslog natively but in most distribution, it is not enabled. To use this feature, you need to recompile your shell.

I found this not very convenient but the good point is that it cannot be disabled by the user (except if he switches his shell to another shell or another Bash binary). You just have to define "SYSLOG_HISTORY" in config-top.h:

$ vi config-top.h
#define SYSLOG_HISTORY
#if defined (SYSLOG_HISTORY)
#  define SYSLOG_FACILITY LOG_USER
#  define SYSLOG_LEVEL LOG_INFO
#endif

./configure
make install

Assim, parece que, embora o recurso esteja disponível no Bash 4.1+, é provável que não seja compilado por padrão com o Bash na maioria das distros populares.

Eu não encontrei um método para ver com quais opções um dado Bash foi compilado, então, para responder a essa questão, você provavelmente precisará olhar para o arquivo .spec do upstream usado ao construir o BPM RPM, por exemplo nas distribuições do Redhat, a mesma abordagem pode ser usada para distribuições baseadas no Debian.

Como confirmação eu olhei no arquivo Bash .spec para o Bash incluído no CentOS 7.2.1511 e ele não está ativado:

$ grep configure bash.spec
%configure --with-bash-malloc=no --with-afs
- Use the configure macro instead of calling ./configure directly

Rolando seu próprio RPM

Aqui estão os passos que usei para criar meu próprio Bash usando a essência do que os detalhes acima explicaram.

download & instalar fonte

Para começar eu baixei um RPM de origem (SRPM) Bash que está disponível para o CentOS 7.x. Depois de baixá-lo, instalei-o no meu diretório rpmbuild :

$ rpmdev-setuptree
$ rpm -ivh bash-4.2.46-20.el7_2.src.rpm
patch

Isso descompactará os arquivos em rpmbuild/SPEC & %código%. Agora vamos fazer uma cópia do conteúdo do arquivo Bash rpmbuild/SOURCES descompactado usando estas etapas:

$ cd rpmbuild/SOURCES
$ tar zxf bash-4.2.tar.gz
$ cp -prf bash-4.2 bash-4.2-orig
$ cd bash-4.2

Edite tar.gz e faça com que pareça:

/* Define if you want each line saved to the history list in bashhist.c:
   bash_add_history() to be sent to syslog(). */
#define SYSLOG_HISTORY
#if defined (SYSLOG_HISTORY)
#  define SYSLOG_FACILITY LOG_LOCAL1
#  define SYSLOG_LEVEL LOG_DEBUG
#endif

Edite rpmbuild/SOURCES/bash-4.2/config-top.h e a função rpmbuild/SOURCES/bash-4.2/bashhist.c fique assim:

void
bash_syslog_history (line)
     const char *line;
{
  char trunc[SYSLOG_MAXLEN];

  if (strlen(line) < SYSLOG_MAXLEN)
    syslog (SYSLOG_FACILITY|SYSLOG_LEVEL, "HISTORY: PID=%d UID=%d USER=%s CMD=%s", getpid(), current_user.uid, current_user.user_name, line);
  else
    {
      strncpy (trunc, line, SYSLOG_MAXLEN);
      trunc[SYSLOG_MAXLEN - 1] = '
$ cd $HOME/rpmbuild/SOURCES
$ diff -Npru bash-4.2-orig bash-4.2 > bash_history_rsyslog.patch
'; syslog (SYSLOG_FACILITY|SYSLOG_LEVEL, "HISTORY: PID=%d UID=%d USER=%s CMD(TRUNCATED)=%s", getpid(), current_user.uid, current_user.user_name, trunc); } }

Agora gere um arquivo bash_syslog_history que inclua nossas alterações nesses dois arquivos:

# history syslog
Patch144: bash_history_rsyslog.patch
...
...
%patch144 -p1 -b .history_rsyslog

Adicione essas linhas a .patch . Coloque essas linhas nos locais apropriados no arquivo SPEC:

$ cd $HOME/rpmbuild/SPEC
$ rpmbuild -ba bash.spec
construir

Agora construa:

...
Processing files: bash-debuginfo-4.2.46-20.el7.centos.x86_64
Provides: bash-debuginfo = 4.2.46-20.el7.centos bash-debuginfo(x86-64) = 4.2.46-20.el7.centos
Requires(rpmlib): rpmlib(FileDigests) <= 4.6.0-1 rpmlib(PayloadFilesHavePrefix) <= 4.0-1 rpmlib(CompressedFileNames) <= 3.0.4-1
Checking for unpackaged file(s): /usr/lib/rpm/check-files /home/vagrant/rpmbuild/BUILDROOT/bash-4.2.46-20.el7.centos.x86_64
Wrote: /home/vagrant/rpmbuild/RPMS/x86_64/bash-4.2.46-20.el7.centos.x86_64.rpm
Wrote: /home/vagrant/rpmbuild/RPMS/x86_64/bash-doc-4.2.46-20.el7.centos.x86_64.rpm
Wrote: /home/vagrant/rpmbuild/RPMS/x86_64/bash-debuginfo-4.2.46-20.el7.centos.x86_64.rpm
Executing(%clean): /bin/sh -e /var/tmp/rpm-tmp.nGworU
+ umask 022
+ cd /home/vagrant/rpmbuild/BUILD
+ cd bash-4.2
+ rm -rf /home/vagrant/rpmbuild/BUILDROOT/bash-4.2.46-20.el7.centos.x86_64
+ exit 0

O final desta compilação será assim:

$ sudo rpm -ivh --force $HOME/rpmbuild/RPMS/x86_64/bash-4.2.46-20.el7.centos.x86_64.rpm
Preparing...                          ################################# [100%]
Updating / installing...
   1:bash-4.2.46-20.el7.centos        ################################# [100%]
instalar

Depois de concluir, podemos instalar o RPM resultante:

$ sudo vim /etc/rsyslog.conf
...
...
$ModLoad imudp
$UDPServerRun 514

$ModLoad imtcp
$InputTCPServerRun 514

...
...

#### GLOBAL DIRECTIVES ####
$template IpTemplate,"/var/log/bash-log/%FROMHOST-IP%.log"
*.* ?IpTemplate
& ~

...
...
configure o rsyslog

Agora modifique $HOME/rpmbuid/SPEC/bash.spec config do rsyslog:

$ sudo systemctl restart rsyslog

Em seguida, reinicie o Rsyslog:

$ sudo -Es
$ ls
teste & confirme

Agora, execute uma nova instância do Bash como root e execute alguns comandos:

$ tail /var/log/bash-log/127.0.0.1.log
2018-07-19T23:23:37.568131-04:00 centos7 bash: HISTORY: PID=12511 UID=1000 USER=vagrant CMD=sudo -Es
2018-07-19T23:23:37.573825-04:00 centos7 sudo: vagrant : TTY=pts/0 ; PWD=/home/vagrant/rpmbuild/SOURCES ; USER=root ; COMMAND=/bin/bash
2018-07-19T23:23:37.589258-04:00 centos7 systemd-logind: Got message type=signal sender=org.freedesktop.DBus destination=n/a object=/org/freedesktop/DBus interface=org.freedesktop.DBus member=NameOwnerChanged cookie=4454 reply_cookie=0 error=n/a
2018-07-19T23:23:37.590633-04:00 centos7 dbus[588]: [system] Activating service name='org.freedesktop.problems' (using servicehelper)
2018-07-19T23:23:37.590806-04:00 centos7 dbus-daemon: dbus[588]: [system] Activating service name='org.freedesktop.problems' (using servicehelper)
2018-07-19T23:23:37.592160-04:00 centos7 dbus[588]: [system] Activated service 'org.freedesktop.problems' failed: Failed to execute program /lib64/dbus-1/dbus-daemon-launch-helper: Success
2018-07-19T23:23:37.592311-04:00 centos7 dbus-daemon: dbus[588]: [system] Activated service 'org.freedesktop.problems' failed: Failed to execute program /lib64/dbus-1/dbus-daemon-launch-helper: Success
2018-07-19T23:23:37.602174-04:00 centos7 systemd-logind: Got message type=signal sender=org.freedesktop.DBus destination=n/a object=/org/freedesktop/DBus interface=org.freedesktop.DBus member=NameOwnerChanged cookie=4455 reply_cookie=0 error=n/a
2018-07-19T23:23:38.520300-04:00 centos7 bash: HISTORY: PID=12585 UID=0 USER=root CMD=ls
2018-07-19T23:23:49.210406-04:00 centos7 bash: HISTORY: PID=12585 UID=0 USER=root CMD=tail /var/log/bash-log/127.0.0.1.log

E siga o arquivo de log, /etc/rsyslog.conf :

$ grep configure bash.spec
%configure --with-bash-malloc=no --with-afs
- Use the configure macro instead of calling ./configure directly

Observe as /var/log/bash-log/127.0.0.1.log linhas neste log? Estes são os comandos que acabamos de executar, um CMD=... & ls .

Pré-construídos?

Para ajudar as pessoas com isso, tomei a liberdade de construir o BPM RPM com as modificações feitas no Copr.

por 19.07.2018 / 01:32