Linux close tcp connection

Terminate existing tcp connection

Is there a way to kill off an existing connection?? For example, 192.168.1.120 is connected to be via port 8080. I would like to know how to terminate that connection? Many thanks!

Is it a connection from inside your program to something else, or a connection to a server socket in your program, or a completely external connection between other programs?

On linux you can use killcx. See my answer to «[How to forcibly close a socket in TIME_WAIT?][1]» [1]: stackoverflow.com/questions/41602/…

2 Answers 2

Since this question is tagged C++ (and I had the same question), I presume that the OP wanted an example that uses the Windows API. I’ve done this using the GetTcpTable2 and SetTcpEntry APIs. You’ll need to call GetTcpTable2 and filter the results to the connection you want to terminate, then pass it to SetTcpEntry . Note that I took a bit of a shortcut with allocating memory for GetTcpTable2 , so if you’re writing production code, you’ll want to read the Microsoft documentation on how best to correctly use the API.

Feel free to use the code I wrote and published under the MIT licence on Github:

It looks like there’s an equivalent for enumerating the connections ( GetTcp6Table2 ), but I can’t find an IPv6 equivalent to SetTcpEntry , unfortunately.

Easiest way (without external software) is to kill and/or restart the process that’s watching that port. That’ll kill off every connection used by that process, though, so it’s not something you normally want to do on a server.

To find out which process is handling the connection on your side, you can say netstat -anp in Linux, or netstat -anb in Windows. Note, in Windows, netstat can be quite slow in backtracking from a socket to a process.

Читайте также:  Аналог файла hosts linux

If you’re using Windows, and don’t mind downloading something, check out SysInternals’ TCPView. Lets you see what ports are open, and what’s using them. It can even kill connections, IIRC, though i forget whether it’s by simply resetting the connection or by killing the process using it.

Источник

Как закрыть TCP подключение

TCP протокол используется для доступа к SSH серверу, доступа к веб-сайтам и во многих других случаях.

TCP протокол устанавливает подключение для инициализации которого выполняется трёхэтапное рукопожатие, в процессе использования этого подключения происходит контроль целостности передачи данных и повторная передача повреждённых или неполученных пакетов.

В целях контроля нагрузки на сеть, либо для симуляции или выполнения сетевых атак может понадобиться принудительно отключить установленное сетевое подключение.

В этой заметке будет рассказано о нескольких инструментах, с помощью которых вы можете принудительно закрыть TCP подключение.

Как разорвать TCP подключение используя утилиту tcpkill

Tcpkill — это сетевая служебная программа, которая может использоваться для уничтожения соединений с определенным хостом, сетью, портом или их комбинацией. Программа tcpkill входит в пакет dsniff.

sudo tcpkill -i ИНТЕРФЕЙС -9 port ПОРТ sudo tcpkill -i ИНТЕРФЕЙС -9 host IP_ИЛИ_ДОМЕН

Например, я хочу отключить SSH подключение (22й порт) на интерфейсе wlo1:

sudo tcpkill -i wlo1 -9 port 22

Фильтры для подключений могут комбинироваться — вы можете использовать любые варианты Фильтров tcpdump и pcap, больше примеров смотрите в Руководстве по tcpdump.

Принцип работы tcpkill основан на том, что она анализирует передаваемый tcp трафик, вычисляет правильное значение пакета в последовательности и отправляет пакеты для сброса соединения. То есть эта программа может работать только для активных соединений, которые обмениваются трафиком после запуска tcpkill.

Как оборвать TCP соединение с помощью killcx

Killcx — это скрипт на Perl для закрытия TCP подключений в Linux независимо от их состояния (полуоткрытые, установоленные, ожидающие или закрывающиеся).

Killcx работает по следующему принципу: программа создаёт фальшивый SYN пакет с фиктивным номером в последовательности, спуфит удалённый IP/порт клиента и отправляет его на сервер. Это приведёт к ответвлению дочернего процесса, который будет захватывать ответ сервера, извлечёт 2 магических значения из пакета ACK и будет использовать их для отправки спуфленного (поддельного) пакета RST. Затем подключение будет закрыто.

Читайте также:  Linux file space left

Обратите внимание, что SYN отправляется для того, что если по каким-либо причинам подключение застряло (нет входящих/исхоодящих пакетов), killcx всё равно сможет закрыть его.

Как установить Killcx

Начните с установки зависимостей.

Установка зависимостей Killcx в Debian, Linux Mint, Ubuntu, Kali Linux и их производные:

sudo apt install libnet-rawip-perl libnet-pcap-perl libnetpacket-perl

Установка зависимостей Killcx в Arch Linux, BlackArch и их производные:

sudo pacman -S perl-net-rawip perl-net-pcap perl-netpacket

Далее во всех системах одинаково:

wget -O killcx-1.0.3.tgz https://sourceforge.net/projects/killcx/files/killcx/1.0.3/killcx-1.0.3.tgz/download tar xvzf killcx-1.0.3.tgz sudo mv killcx-1.0.3/killcx /usr/bin/killcx rm -rf killcx-1.0.3* killcx
destip : IP удалённого хоста destport : порт удалённого хоста ИНТЕРФЕЙС (опционально) : сетевой интерфейс (eth0, lo etc). Помните, что во многих случаях использование 'lo' (loopback) даст лучшие результаты, особенно когда подключение ещё не, или уже не в состоянии ESTABLISHED (SYN_RECV, TIME_WAIT и т.д.).
killcx 10.11.12.13:1234 killcx 10.11.12.13:1234 eth0

Источник

Рабочий метод разрыва конкретного активного соединения из командной строки linux (drop/kill/cut/close ESTABLISHED connection)

Иногда бывает необходимо принудительно разорвать активное соединение. Самый распространенный способ:

Проблема в том, что один воркер может одновременно обслуживать несколько соединений, поэтому правильнее будет убить соединение а не воркер. Для этого на многих форумах рекомендуют использовать tcpkilll, cutter или awk+hping3. Однако, хоть эти утилиты и находятся в официальных репозиториях, мне не удалось заставить их разрывать соединения.

После продолжительных поисков был обнаружен perl скрипт killcx, разрывающий соединение по удаленному хосту и порту.

killcx 94.133.119.242:4403

[PARENT] checking connection with [94.133.119.242:4403]
[PARENT] found connection with [78.220.184.126:80] (ESTABLISHED)
[PARENT] forking child
[CHILD] interface not defined, will use [eth0]
[CHILD] setting up filter to sniff ACK on [eth0] for 5 seconds
[CHILD] hooked ACK from [77.220.184.126:80]
[CHILD] found AckNum [3091573605] and SeqNum [3105164779]
[CHILD] sending spoofed RST to [78.220.184.126:80] with SeqNum [3091573605]
[CHILD] sending RST to remote host as well with SeqNum [3105164779]
[CHILD] all done, sending USR1 signal to parent [13723] and exiting
[PARENT] received child signal, checking results.
=> success : connection has been closed !

Читайте также:  Linux copy from folder

Для его работы требуется целый набор библиотек.

apt-get install \
libpcap0.8 \
libpcap-dev \
libnet-pcap-perl \
libyaml-perl \
libyaml-dev \
libyaml-0-1 \
-y

cpan -i \
Net::RawIP \
NetPacket::Ethernet

Источник

Close established TCP connection on Linux

I am not able to find an answer to a simple thing I will try to achive: once a tcp connection is established to my linux server, let’s say ssh / tcp 22 or x11 / tcp 6000 display -> how do I close this connection without killing the process (sshd / x11 display server). I saw also some suggestoin to use iptables, but it does not work for me, the connection is still visible in netstat -an. would be good if someone can point me to the right direction. what I tried so far

tcpkill: kills the process, not good for me iptables: does not close the established connection, but prevent further connections. 

Attach to the process with a debugger, then call shutdown() followed by close() , or just close() , on the appropriate file descriptor. Then hope the process can handle that.

2 Answers 2

Ok, I found at least one solution (killcx) which is working. Maybe we will be able to find an easier solution. Also, i saw the comment from «zb» — thanks — which might also work, but I was not able to find a working syntax, since this tool seems to be really useful but complex. So here is an example how to work with the 1. solution which is working for me:

netstat -anp | grep 22 output: tcp 0 0 192.168.0.82:22 192.168.0.77:33597 VERBUNDEN 25258/0 iptables -A INPUT -j DROP -s 192.168.0.77 (to prevent reconnect) perl killcx.pl 192.168.0.77:33597 (to kill the tcp connection) 

killcx can be found here: http://killcx.sourceforge.net/ it «steals» the connection from the foreign host (192.168.0.77) and close it. So that solution is working fine, but to complex to setup quickly if you are under stress. Here are the required packages:

apt-get install libnetpacket-perl libnet-pcap-perl libnet-rawip-perl wget http://killcx.sourceforge.net/killcx.txt -O killcx.pl 

however, would be good to have an easier solution.

Источник

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