Log users commands linux

How can you log every command typed

How can you log every command someone has entered into the shell? I’m asking on both the basis of protecting yourself if you are logged into someone else’s server and something breaks, or if someone else is logged into your server (either intentionally or maliciously). Even a novice can bypass history with unset history or create a new shell to hide their tracks. I’m curious how the senior Linux admins track what commands have been entered or what changes made to the system.

2 Answers 2

-a exit,always -F arch=b64 -S execve -a exit,always -F arch=b32 -S execve 

to /etc/audit/audit.rules every executed commands will be logged. See: https://whmcr.com/2011/10/14/auditd-logging-all-commands/

Then send it to a syslog server.

Actually, I noticed that in the man page for exec it says that «The exec() family of functions replaces the current process image with a new process image. The functions described in this manual page are front-ends for execve(2) .» So while I’m not sure about execveat I can feel assured about the exec family.

you can also make a look at tlog. it’s not yet in debian (bugs.debian.org/cgi-bin/bugreport.cgi?bug=886927) but integrates very will into cockpit and is natively supported on redhat.

You can use the script command. This command is not included in POSIX, but you’ll find it useful to store in a file all keystrokes as well as output and error messages. You can later view the file. If you are doing some important work and wish to keep a log of all your activities, you should invoke this command immediately after you log in:

$ script
Script started, file is typescript
$ _ Note that this is another shell—child of the login shell

The prompt returns and all your keystrokes (including the one used to backspace) that you now enter here get recorded in the file ‘typescript’. After your recording is over, you can terminate the session by entering exit.
Note: If you enter script filename, the session will be stored in the file filename rather than typescript, i.e, typescript is the default if no specific filename is specified.

You can now use cat filename or cat typescript, whichever the case may be, to view the recorded session.

If you wish to append a new session to an old file use: script -a Appends the new session to typescript, same default rule applies here too

This is one way in which a system admin can keep track of the sessions. Hope it has been informative and useful. Cheers!

Источник

Использование screen для логирования действий (аудита) пользователей в Linux

. this may break programs which run the login shell defined in /etc/passwd for various commands…
. It then becomes hard to do anything with your account other than log in. Also, your sysadmin probably doesn’t have screen in /etc/shells.

Читайте также:  Сервер 1с без ключа linux

Создаём скрипт для запуска screen, чтобы при запуске командной оболочки bash (ведь у вас bash, правда?) все пользователи использовали этот файл и загружались в screen по умолчанию с включённым логированием. При выходе из screen – сессия закрывается:
vi /usr/local/bin/get_in.sh

#!/bin/sh SCREEN=/usr/bin/screen KILL=/bin/kill ## Check if we are already in screen ($STY is set) if [ -z "$STY" ]; then $SCREEN -LARR -S Shared -c /etc/screenrc ## Force SHELL close on exit - we don't want to allow users to escape logging outside screen $KILL -SIGHUP $PPID fi 

Что мы имеем:
-L — направить весь лог в файл (куда именно — см. директиву logfile в файле /etc/screenrc ниже)
-A — Адаптировать размеры окон к размеру текущего терминала. Взято отсюда.
-RR — Переподключить сессию и, если необходимо, отсоединить (detach) её или создать заново. Используется первая сессия, если больше чем одна доступна. В случае отключения по ^a + d, при повторном входе откроется эта же сессия этого же пользователя.
-c — мы чётко указываем, какой конфигурационный файл использовать, чтобы избежать возможности отключения логирования и переназначения опций пользователями, к примеру созданием файла в ~/.screenrc.
-S — Назначаем сессии понятное имя. У каждого пользователя может быть одно и то же имя.

Делаем скрипт исполняемым:
chmod 0755 /usr/local/bin/get_in.sh

Делаем так, чтобы все использовали этот скрипт. Для этого в конец файла /etc/bash.bashrc добавляем строку:
/usr/local/bin/get_in.sh

Корректируем файл /etc/screenrc:

## Выбираем, хотим ли мы видеть заметку о правообладателях во время запуска. По умолчанию включено (on), как вы заметили. startup_message off # default: on ## Отключаем визуальный сигнал - включается обычное "пикание" как в shell vbell off ## Размер буфера прокрутки увеличиваем до 4096. Значение по умолчанию - 100. defscrollback 4096 # default: 100 ## Устанавливаем командную оболочку (shell), которая будет использоваться при создании новых окон. Переназначает значение переменной окружения $SHELL. Если команда начинается с символа '-' , то командная оболочка будет запущена как login-shell. defshell -/bin/bash ## Влияет на копирование текста комадной ^a+[ . crlf off # default: off ## Добавляет симпатичную строку состояния внизу экрана. caption always "% %H | %%?%-w%?%%n*%f %t%?(%u)%?%%?%+w%? %=|% %l %| %%%D, %m/%d/%Y | %%%c %" ## Set terminal cap info termcapinfo xterm* 'hs:ts=\E]0;:fs=\007:ds=\E]0;\007' hardstatus off ## Отключаем возможность отключения логирования из самой сессии screen (^a + H) bind H ## Устанавливаем расположение и именование лог-файлов logfile /var/log/screen/$USER@%H-%Y%m%d-%c:%s.log ## By default, screen uses an 8-color terminal emulator. Use the following line to enable more colors, which is useful if you are using a more-capable terminal emulator: term screen-256color ## Устанавливает функцию записи отметок времени в лог-файл logtstamp on 

Не забываем создать директорию для логов:

В Debian, чтобы в screen работало автозавершение команд (bash_completion), необходимо раскомментировать в /etc/bash.bashrc:

# enable bash completion in interactive shells if [ -f /etc/bash_completion ] && ! shopt -oq posix; then . /etc/bash_completion fi

Уважаемый 1ex подсказал решение, как с помощью wrapper-а для ssh логировать команды, выполняемые без входа в интерактивный режим bash вида: ssh user@host «ls -l». Для этого необходимо:
в /etc/ssh/sshd_config указать ссылку на обработку wrapper-ом:

ForceCommand /etc/ssh/hook.sh 
#!/bin/sh if [ ! -z "$" ]; then echo "User "$" remotely runs a command: $" >> /var/log/screen/$USER@`hostname`-`date +%Y%m%d-%H:%M:%S`-command.log bash -c "$SSH_ORIGINAL_COMMAND" else cat /etc/motd $ fi 

Этим мы добиваемся, чтобы все такие команды (и только команды — без информации, что выводится на экране) логировались в ту же директорию и будут дополнены суффиксом «-command»:

Читайте также:  Postgresql конфигурационный файл linux

Ну вот и всё. Теперь при подключении все пользователи (включая root — будьте осторожны, если потеряете возможность входа!) будут работать в screen, который запускается из bash. При выходе из screen, родительский bash закрывается и соединение прерывается. Если необходимо оставить работать процессы в фоне, то для выхода используем ^a+d. При следующем подключении эта сессия подключится автоматически.

Для дальнейшего изучения:

  • Так как в логи пишется вывод команд — они могут занимать большое количество места. Необходимо предусмотреть методы сжатия для уменьшения объёма/трафика
  • Лучшее место для логов — удалённая машина и далее обработку производить там, так как логи на локальной машине создаются с uid/guid пользователя и могут быть им удалены/изменены. Предполагается использование syslog.
  • Возможно, есть методы обойти screen и, соответственно, логирования при этой конфигурации. Хотелось бы услышать их и внести изменения

Используемые источники:

Update:

SCREEN=`which screen` KILL=`which kill` 
SCREEN=/usr/bin/screen KILL=/bin/kill 

На данный момент существуют 2 метода обхода логирования команд:

1) Подсказана kiltum: команды типа ssh user@host «ls -l» не логируются. В этом случае команды выполняются как /bin/bash -c , при этом нужный /etc/bash.bashrc не читается.
Уважаемый 1ex подсказал решение с помощью wrapper-а для ssh. Теперь все команды такого типа логируются. Изменения в текст внесены.
2) Подсказана ForeverYoung: команда screen -X log отключает логирование.
Возможности отключить эту особенность пока что нету, поэтому необходимо применять административные меры к пользователям, кто запускает эту команду (сама эта команда всё равно будет записана в лог).
Лучшие решения приветствуются.

ИТОГИ:

Как выяснилось screen не совсем предназначен для решения такого рода задач, а именно принудительного логирования команд и их вывода без возможности отключения логирования. Это приводит к тому, что приходится дополнительно править другие файлы.
Как порекомендовал уважаемый amarao для решения такого рода задач лучше посмотреть на другие решения:
а) сниффинга всего трафика, проходящего через псевдотерминалы (более серьёзно). kiltumподсказал conspy. Slipeer предложил Snoopy Logger.
б) систем аудита (SELinux/Apparmor/etc), которые будут записывать реально всё выполняемое.
Но эти решения выходят за рамки данной статьи.

Считаю, что несмотря на недостатки, использование screen для логирования действий пользователей и выводимой на экран информации в Linux оправдано, ввиду несложности реализации, а главное — простоты чтения логов (в отличие от auditd, напимер).

Источник

Where is the log of used commands in Linux?

command provides the list of commands we used previously but its limit is less. New commands are overwritten on old commands then old commands are missing. I think somewhere the log of the commands is stored in the system. Is that log available to open and read? If possible can we change the maximum size of log that it can handle? Is the output of history command depends upon the login-user?

5 Answers 5

A simple solution is to increase the number of commands saved and returned by history . If you use bash, add this line to your ~/.profile :

export HISTSIZE=100000 export HISTFILESIZE=999999 
 HISTFILESIZE The maximum number of lines contained in the history file. When this variable is assigned a value, the history file is trun‐ cated, if necessary, to contain no more than that number of lines by removing the oldest entries. The history file is also truncated to this size after writing it when a shell exits. If the value is 0, the history file is truncated to zero size. Non-numeric values and numeric values less than zero inhibit truncation. The shell sets the default value to the value of HISTSIZE after reading any startup files. HISTSIZE The number of commands to remember in the command history (see HISTORY below). If the value is 0, commands are not saved in the history list. Numeric values less than zero result in every command being saved on the history list (there is no limit). The shell sets the default value to 500 after reading any startup files. 

@gafoor yes, the history file I mention in my answer. Nothing else by default. If you set the variables I shows, you will keep a list of thousands of commands.

Читайте также:  Проверить версию питона на линукс

The file ~/.bash_history saves the list of executed commands. At least in CentOS this file exists, I don’t know if it exists in other distros.

@AbdulGafoor yes, but that’s what you see when you run history . It will only have as many commands as those returned by history . To keep more, you need to set the variables I show in my answer.

This file also exists in Mac OSX. You can type vim ~/.bash_history to see the contents of the file under Mac.

It’s the HISTFILE variable which sets the location history file, which by default (for bash) is ~/.bash_history

There is no such log, at least not by default.

There are tools you can install, like acct («GNU Accounting utilities for process and login accounting») which can keep track of all programs executed on the system.

acct is packaged for most (probably all except tiny-distros) linux distros. The home page is at http://www.gnu.org/software/acct/

acct provides the following commands, lastcomm probably does what you’re asking for:

ac prints statistics about users’ connect time. ac can tell you how long a particular user or group of users were connected to your system, printing totals by day or for all of the entries in the wtmp file.

accton turns accounting on or off.

lastcomm lists the commands executed on the system, most recent first, showing the run state of each command. With last, you can search the acct file for a particular user, terminal, or command.

sa summarizes the information in the acct file into the savacct and usracct file. It also generates reports about commands, giving the number of invocations, cpu time used, average core usage, etc.

dump-acct dump-utmp display acct and utmp files in a human-readable format.

Источник

Оцените статью
Adblock
detector