Как проверить историю IP адресов для SSH сессий
В случае если сервер на Linux был взломан, возникает необходимость собрать информацию, например, получить время и IP адреса последних SSH сессий. Это может помочь не только установить источник опасности, но и, например, ответить на вопрос: был ли подобран пароль (или скомпрометирован сертификат) SSH либо злоумышленник воспользовался уязвимостью программного обеспечения.
К счастью, в дистрибутивах Linux хранятся журналы входа в систему, как по сети, так и для пользователей, который непосредственно сидят перед компьютером.
IP адрес предыдущего подключения по SSH
При каждом подключении по SSH выводится строка с IP, с которого было сделано предыдущее подключение, также показывается дата и время этого подключения:
История IP адресов SSH подключений
Кроме последней сессии, в системе хранится информация обо всех успешных входах за последние месяцы. Эта информация содержится в файле utmp / wtmp. На самом деле, файл utmp могут использовать различные программы (не только SSH), которые хотят сохранить информацию о входе пользователя.
Во многих дистрибутивах имеется файл /var/log/wtmp, куда программы записывают входы в систему. Проверить последние записи можно командой:
Все записи, в которых встречаются IP адреса — были сделаны по SSH подключению.
Записи без IP адресов — это входы пользователей, находящихся непосредственно перед компьютером.
Дополнительно вы можете проверить другие файлы журналов: /var/log/secure (на дистрибутивах на основе RH) или /var/log/auth.log (на дистрибутивах на основе Debian). В этих файлах служба sshd обычно хранит следы сделанных подключений, даже если они не стали результатом успешных входов (как это делают utmp/wtmp, которые сохраняют только информацию об успешных входах).
Служба sshd на IIRC Solaris (которая необязательно является sshd службой OpenSSH) хранит эту информацию в /var/adm/messages.
При этом необходимо помнить, что если атакующий получил доступ с правами суперпользователя, то есть скомпрометирован аккаунт root или другого пользователя с повышенными привилегиями, то все записи в файлах /var/log/wtmp или /var/adm/messages могут быть изменены атакующим. Для защиты от этого необходимо регулярно выгружать журналы в безопасное хранилище.
Как узнать, кто в настоящий момент подключён по SSH
Чтобы увидеть пользователей, вошедших в систему, используйте любую из следующих команд:
Следующие команды также покажут активные SSH сессии — у каждой из них различается набор выводимой информации, поэтому вы можете выбрать ту из них, которая вам больше всего подходит:
6 commands to check and list active SSH connections in Linux
How to check active SSH connections in Linux. Show SSH connection history. How to show active ssh sessions in Linux. List all the active SSH connections in Unix. Find out all the currently active ssh connections on any Linux node. Which all tools can be used to list all the active ssh connections in Linux. Show active SSH sessions. Check ssh connection history using log files in Linux.
Some more more articles you may be interested on similar topics:
- Step-by-Step Guide to Install and configure fail2ban with sshd jail to prevent brute force attacks in Linux
- Different ssh authentication methods available to secure connection using sshd_config in Linux
- How to restrict or allow ssh only from certain users, groups or hosts in Linux
Check active SSH connections
There are various commands and tools available in Linux which can be used to check active SSH connections or sessions on your Linux node. In this article I will share a list of tools which can be used to get the list of active SSH connections. If you are aware of any more commands to show active ssh sessions then please let me know via comment section.
1. Using ss command
ss is used to dump socket statistics. It allows showing information similar to netstat . It can display more TCP and state information than other tools. We will use grep function to only get the list of active SSH sessions on our local host
From the above example we know that there are three hosts which are currently connected to our node3. We have active SSH connections from 10.0.2.31, 10.0.2.30 and 10.0.2.2
2. Using last command
last searches back through the file /var/log/wtmp (or the file designated by the -f flag) and displays a list of all users logged in (and out) since that file was created. Names of users and tty’s can be given, in which case last will show only those entries matching the arguments.
Using this command you can also get the information about the user using which the SSH connection was created between server and client. So below we know the connection from 10.0.2.31 is done using ‘deepak‘ user, while for other two hosts, ‘root‘ user was used for connecting to node3.
Here I am grepping for a string «still» to get all the patterns with » still logged in «. So now we know we have three active SSH connections from 10.0.2.31, 10.0.2.30 and 10.0.2.2
3. Using who command
who is used to show who is logged on on your Linux host. This tool can also give this information
Using this command we also get similar information as from last command. Now you get the user details used for connecting to node3 from source host, also we have terminal information on which the session is still active.
4. Using w command
w displays information about the users currently on the machine, and their processes. This gives more information than who and last command and also serves our purpose to get the list of active SSH connections. Additionally it also gives us the information of the running process on those sessions.
Using w command you will also get the idle time details, i.e. for how long the session is idle. If the SSH session is idle for long period then it is a security breach and it is recommended that such idle SSH session must be killed, you can configure your Linux host to automatically kill such idle SSH session.
5. Using netstat command
Similar to ss we have netstat command to show active ssh sessions. Actually we can also say that ss is the new version of netstat. Here we can see all the ESTABLISHED SSH sessions from remote hosts to our localhost node3. it is also possible that one or some of these active ssh connections are in hung state so you can configure your host to automatically disconnect or kill these hung or unresponsive ssh sessions in Linux.
6. Using ps command
Now to show active ssh sessions, ps command may not give you accurate results like other commands we discussed in this article but it can give you some more additional information i.e. PID of the SSHD process which are currently active and connected.
Check ssh connection history
To get the ssh connection history you can always check your SSHD logs for more information on connected or disconnected SSH session. Now the sshd log file may vary from distribution to distribution. On my RHEL 7.4 my sshd logs are stored inside /var/log/sshd
Lastly I hope the steps from the article to check active SSH connections and ssh connection history in Linux was helpful. So, let me know your suggestions and feedback using the comment section.
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Как посмотреть текущие SSH подключения?
хотя показаны две строки, но, фактически, это одно соединение к локальному компьютеру ( 10.0.0.1 , порт 22 ( ssh )) с удалённого ( 10.0.0.2 , порт 59964). просто процесс sshd, выполняющийся от имени root, создал дочерний процесс, но уже от имени alice.
пояснения (см. $ man lsof ):
- -n — не пытаться преобразовывать ip-адреса в доменные имена (может значительно ускорить работу)
- -a — применить логическую операцию «и» («and»)
- -itcp — показать tcp-сокеты
- -stcp:established — показать tcp-сокеты, находящиеся в состоянии «established»
- -c sshd — показать процессы, запущенные из бинарных файлов, имена которых начинаются строкой sshd
почему два фильтры -itcp и -c sshd вместо одного -itcp:22 ?
потому что в этом случае в вывод попадут и процессы ssh, запущенные локально и подключившиеся к 22-ым портам каких-нибудь машин. к тому же, в случае, если ваш sshd слушает и/или порт(ы), отличный(е) от 22-го, то такие соединения просто не попадут в вывод.
List all connected SSH sessions?
I just SSH’d into root, and then SSH’d again into root on the same machine. So I have two windows open both SSH’d into root on my remote machine.
From the shell, how can I see a list of these two sessions?
7 Answers 7
who or w ; who -a for additional information.
These commands just show all login sessions on a terminal device. An SSH session will be on a pseudo-terminal slave ( pts ) as shown in the TTY column, but not all pts connections are SSH sessions. For instance, programs that create a pseudo-terminal device such as xterm or screen will show as pts . See Difference between pts and tty for a better description of the different values found in the TTY column. Furthermore, this approach won’t show anybody who’s logged in to an SFTP session, since SFTP sessions aren’t shell login sessions.
I don’t know of any way to explicitly show all SSH sessions. You can infer this information by reading login information from utmp / wtmp via a tool like last , w , or who like I’ve just described, or by using networking tools like @sebelk described in their answer to find open tcp connections on port 22 (or wherever your SSH daemon(s) is/are listening).
A third approach you could take is to parse the log output from the SSH daemon. Depending on your OS distribution, SSH distribution, configuration, and so on, your log output may be in a number of different places. On an RHEL 6 box, I found the logs in /var/log/sshd.log . On an RHEL 7 box, and also on an Arch Linux box, I needed to use journalctl -u sshd to view the logs. Some systems might output SSH logs to syslog. Your logs may be in these places or elsewhere. Here’s a sample of what you might see:
The logs show when sessions open and close, who the session belongs to, where the user is connecting from, and more. However, you’re going to have to do a lot of parsing if you want to get this from a simple, human-readable log of events to a list of currently active sessions, and it still probably won’t be an accurate list when you’re done parsing, since the logs don’t actually contain enough information to determine which sessions are still active — you’re essentially just guessing. The only advantage you gain by using these logs is that the information comes directly from SSHD instead of via a secondhand source like the other methods.
I recommend just using w . Most of the time, this will get you the information you want.