NetCat: nc - сетевой cat

Средства управление сетью

Модераторы: Olej, vikos

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

NetCat: nc - сетевой cat

Непрочитанное сообщение Olej » 09 июл 2021, 19:40

Olej писал(а):
07 июл 2021, 18:29
Особенность использования варианта OpenBSD версии программы для моих скриптов в том (при используемых опциях-параметрах), что мой клиент не обрабатывает ситуацию EOF со стороны передающего сервера.
Обсуждений того, что netcat реализация OpenBSD не посылает завершающий EOF клиенту (netcat клиенту или любому самописному коду) во множестве обсуждается в сети:

Почему отправка ^ D с netcat не вызывает EOF при чтении из сокета Unix?
Когда netcat сталкивается с EOF на стандартном входе, он может или не может закрыть отправную часть своего TCP-соединения, в зависимости от какой версии netcat он есть.
BSD nc (netcat) не заканчивается на EOF
Хозяин А:
tar cf - stuff | dd | nc -N -l 12987
Хозяин Б:
nc a.example.com 12987 | dd | tar tf -
...
How do I tell nc to close stdout/terminate on host B and terminate on host A.
...
nc establishes a bi-directional connection. I.e. it sends stdin from host B to host A as well as the desired one from A to B.

Используйте -d на хозяине Б, чтобы проигнорировать stdin . -N на хозяине А все еще необходим, чтобы закрыть TCP связь на EOF.
Таким образом,
Хозяин А:
tar cf - stuff | dd | nc -N -l 12987
Хозяин Б:
nc -d a.example.com 12987 | dd | tar tf -
В этом смысле характерно то, что описания публикуемые в сети по netcat (а их великое множество в виду широты использования netcat) относятся к разным реализациям (3-м как мы видели): разные опции командной строки, разный их смысл и т.д.

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

NetCat: nc - сетевой cat

Непрочитанное сообщение Olej » 12 мар 2024, 12:05

Olej писал(а):
07 июл 2021, 18:29
На самом деле их аж 3:
3-я реализация ncat - это от проекта nmap, Introduction:
Ncat is a feature-packed networking utility which reads and writes data across networks from the command line. Ncat was written for the Nmap Project as a much-improved reimplementation of the venerable Netcat. It uses both TCP and UDP for communication and is designed to be a reliable back-end tool to instantly provide network connectivity to other applications and users.

Код: Выделить всё

olej@R420:~$ sudo apt install ncat
[sudo] пароль для olej:
Чтение списков пакетов… Готово
Построение дерева зависимостей… Готово
Чтение информации о состоянии… Готово
Следующие НОВЫЕ пакеты будут установлены:
  ncat
Обновлено 0 пакетов, установлено 1 новых пакетов, для удаления отмечено 0 пакетов, и 0 пакетов не обновлено.
Необходимо скачать 101 kB архивов.
После данной операции объём занятого дискового пространства возрастёт на 253 kB.
Пол:1 http://ubuntu.colocall.net/ubuntu jammy-updates/universe amd64 ncat amd64 7.91+dfsg1+really7.80+dfsg1-2ubuntu0.1 [101 kB]
Получено 101 kB за 1с (85,0 kB/s)
Выбор ранее не выбранного пакета ncat.
(Чтение базы данных … на данный момент установлено 595622 файла и каталога.)
Подготовка к распаковке …/ncat_7.91+dfsg1+really7.80+dfsg1-2ubuntu0.1_amd64.deb …
Распаковывается ncat (7.91+dfsg1+really7.80+dfsg1-2ubuntu0.1) …
Настраивается пакет ncat (7.91+dfsg1+really7.80+dfsg1-2ubuntu0.1) …
Обрабатываются триггеры для man-db (2.10.2-1) …
И сразу же он сам встал вот так:

Код: Выделить всё

olej@R420:~$ update-alternatives --list nc
/bin/nc.openbsd
/bin/nc.traditional
/usr/bin/ncat

Код: Выделить всё

olej@R420:~$ update-alternatives --display nc
nc - ручной режим
  лучшая версия ссылки — /bin/nc.openbsd
  ссылка сейчас указывает на /bin/nc.traditional
  ссылка nc — /bin/nc
  подчинённая nc.1.gz — /usr/share/man/man1/nc.1.gz
  подчинённая netcat — /bin/netcat
  подчинённая netcat.1.gz — /usr/share/man/man1/netcat.1.gz
/bin/nc.openbsd — приоритет 50
  подчинённый nc.1.gz: /usr/share/man/man1/nc_openbsd.1.gz
  подчинённый netcat: /bin/nc.openbsd
  подчинённый netcat.1.gz: /usr/share/man/man1/nc_openbsd.1.gz
/bin/nc.traditional — приоритет 10
  подчинённый nc.1.gz: /usr/share/man/man1/nc.traditional.1.gz
  подчинённый netcat: /bin/nc.traditional
  подчинённый netcat.1.gz: /usr/share/man/man1/nc.traditional.1.gz
/usr/bin/ncat — приоритет 40
  подчинённый nc.1.gz: /usr/share/man/man1/ncat.1.gz
  подчинённый netcat: /usr/bin/ncat
  подчинённый netcat.1.gz: /usr/share/man/man1/ncat.1.gz

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

NetCat: nc - сетевой cat

Непрочитанное сообщение Olej » 12 мар 2024, 12:07

Olej писал(а):
12 мар 2024, 12:05
И сразу же он сам встал вот так:
Хотя любой из 3-х nc можно вызвать напрямую, минуя альтернативы:

Код: Выделить всё

olej@R420:~$ /usr/bin/ncat --help
Ncat 7.80 ( https://nmap.org/ncat )
Usage: ncat [options] [hostname] [port]

Options taking a time assume seconds. Append 'ms' for milliseconds,
's' for seconds, 'm' for minutes, or 'h' for hours (e.g. 500ms).
  -4                         Use IPv4 only
  -6                         Use IPv6 only
  -U, --unixsock             Use Unix domain sockets only
      --vsock                Use vsock sockets only
  -C, --crlf                 Use CRLF for EOL sequence
  -c, --sh-exec <command>    Executes the given command via /bin/sh
  -e, --exec <command>       Executes the given command
      --lua-exec <filename>  Executes the given Lua script
  -g hop1[,hop2,...]         Loose source routing hop points (8 max)
  -G <n>                     Loose source routing hop pointer (4, 8, 12, ...)
  -m, --max-conns <n>        Maximum <n> simultaneous connections
  -h, --help                 Display this help screen
  -d, --delay <time>         Wait between read/writes
  -o, --output <filename>    Dump session data to a file
  -x, --hex-dump <filename>  Dump session data as hex to a file
  -i, --idle-timeout <time>  Idle read/write timeout
  -p, --source-port port     Specify source port to use
  -s, --source addr          Specify source address to use (doesn't affect -l)
  -l, --listen               Bind and listen for incoming connections
  -k, --keep-open            Accept multiple connections in listen mode
  -n, --nodns                Do not resolve hostnames via DNS
  -t, --telnet               Answer Telnet negotiations
  -u, --udp                  Use UDP instead of default TCP
      --sctp                 Use SCTP instead of default TCP
  -v, --verbose              Set verbosity level (can be used several times)
  -w, --wait <time>          Connect timeout
  -z                         Zero-I/O mode, report connection status only
      --append-output        Append rather than clobber specified output files
      --send-only            Only send data, ignoring received; quit on EOF
      --recv-only            Only receive data, never send anything
      --no-shutdown          Continue half-duplex when receiving EOF on stdin
      --allow                Allow only given hosts to connect to Ncat
      --allowfile            A file of hosts allowed to connect to Ncat
      --deny                 Deny given hosts from connecting to Ncat
      --denyfile             A file of hosts denied from connecting to Ncat
      --broker               Enable Ncat's connection brokering mode
      --chat                 Start a simple Ncat chat server
      --proxy <addr[:port]>  Specify address of host to proxy through
      --proxy-type <type>    Specify proxy type ("http", "socks4", "socks5")
      --proxy-auth <auth>    Authenticate with HTTP or SOCKS proxy server
      --proxy-dns <type>     Specify where to resolve proxy destination
      --ssl                  Connect or listen with SSL
      --ssl-cert             Specify SSL certificate file (PEM) for listening
      --ssl-key              Specify SSL private key (PEM) for listening
      --ssl-verify           Verify trust and domain name of certificates
      --ssl-trustfile        PEM file containing trusted SSL certificates
      --ssl-ciphers          Cipherlist containing SSL ciphers to use
      --ssl-alpn             ALPN protocol list to use.
      --version              Display Ncat's version information and exit

See the ncat(1) manpage for full options, descriptions and usage examples
Описание Ncat
Инструменты Kali Linux
Режим подключения (connect mode) и режим прослушивания (listen mode)
Ncat работает в двух главных режимах: режим подключения и режим прослушивания. Другие режимы, такие как HTTP прокси сервер, выступают как специальные случаи двух основных режимов. В режиме подключения Ncat работает как клиент. В режиме прослушания это сервер.
Там же - много примеров использования именно этой реализации NetCat...

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

NetCat: nc - сетевой cat

Непрочитанное сообщение Olej » 12 мар 2024, 12:28

Olej писал(а):
07 июл 2021, 18:29
На самом деле их аж 3:
И ещё - 4-й, из свежих реализаций (судя по их GIT - это 2021 год):

GIT репозиторий кода здесь: https://github.com/calebstewart/pwncat

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

NetCat: nc - сетевой cat

Непрочитанное сообщение Olej » 12 мар 2024, 12:47

Olej писал(а):
12 мар 2024, 12:28
GIT репозиторий кода здесь
pwncat-cs
Naming Changes
Due to the naming conflict with Cytopia's pwncat, I have decided to rename the package to pwncat-cs. This includes renaming the entrypoint so that there are no direct conflicts with Cytopia's project. If you are updating from v0.4.*, the command name will now have changed, and the pcat and pc varianst have been removed. See the most recent release notes for more details.
Написан он на Python (учитывая, что от утилиты для сетевой передачи не нужно особой шустрости ... и гибкость Python - это, пожалуй, разумный выбор)...
Изображение

Устанавливается (из нескольких способов, на "попробовать" ... это не из лучших) простецки:

Код: Выделить всё

olej@R420:~$ pip install pwncat-cs
Defaulting to user installation because normal site-packages is not writeable
Collecting pwncat-cs
  Downloading pwncat_cs-0.5.4-py3-none-any.whl (2.4 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.4/2.4 MB 2.4 MB/s eta 0:00:00
Collecting paramiko-ng<3.0.0,>=2.8.8
  Downloading paramiko_ng-2.8.10-py2.py3-none-any.whl (197 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 197.6/197.6 KB 4.1 MB/s eta 0:00:00
Requirement already satisfied: Jinja2<4.0.0,>=3.0.1 in ./.local/lib/python3.10/site-packages (from pwncat-cs) (3.1.2)
Collecting ZODB3<4.0.0,>=3.11.0
  Downloading ZODB3-3.11.0.tar.gz (55 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 55.1/55.1 KB 3.6 MB/s eta 0:00:00
  Preparing metadata (setup.py) ... done
Requirement already satisfied: PyNaCl<2.0.0,>=1.4.0 in /usr/lib/python3/dist-packages (from pwncat-cs) (1.5.0)
Requirement already satisfied: pycryptodome<4.0.0,>=3.10.1 in /usr/local/lib/python3.10/dist-packages (from pwncat-cs) (3.16.0)
Collecting rich<11.0.0,>=10.4.0
  Downloading rich-10.16.2-py3-none-any.whl (214 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 214.4/214.4 KB 4.0 MB/s eta 0:00:00
Requirement already satisfied: netifaces<0.12.0,>=0.11.0 in /usr/lib/python3/dist-packages (from pwncat-cs) (0.11.0)
Requirement already satisfied: requests<3.0.0,>=2.25.1 in ./.local/lib/python3.10/site-packages (from pwncat-cs) (2.28.2)
Collecting packaging<21.0,>=20.9
  Downloading packaging-20.9-py2.py3-none-any.whl (40 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 40.9/40.9 KB 1.9 MB/s eta 0:00:00
Collecting python-rapidjson<2.0,>=1.0
  Downloading python_rapidjson-1.16-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.7 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.7/1.7 MB 4.3 MB/s eta 0:00:00
Requirement already satisfied: prompt-toolkit<4.0.0,>=3.0.19 in /usr/lib/python3/dist-packages (from pwncat-cs) (3.0.28)
Collecting zodburi<3.0.0,>=2.5.0
  Downloading zodburi-2.6.0-py3-none-any.whl (13 kB)
Requirement already satisfied: MarkupSafe>=2.0 in /usr/lib/python3/dist-packages (from Jinja2<4.0.0,>=3.0.1->pwncat-cs) (2.0.1)
Requirement already satisfied: pyparsing>=2.0.2 in /usr/lib/python3/dist-packages (from packaging<21.0,>=20.9->pwncat-cs) (2.4.7)
Collecting bcrypt>=3
  Downloading bcrypt-4.1.2-cp39-abi3-manylinux_2_28_x86_64.whl (698 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 698.9/698.9 KB 4.3 MB/s eta 0:00:00
Requirement already satisfied: cryptography>=1.6 in /usr/lib/python3/dist-packages (from paramiko-ng<3.0.0,>=2.8.8->pwncat-cs) (3.4.8)
Requirement already satisfied: cffi>=1.4.1 in /usr/local/lib/python3.10/dist-packages (from PyNaCl<2.0.0,>=1.4.0->pwncat-cs) (1.15.1)
Requirement already satisfied: certifi>=2017.4.17 in /usr/lib/python3/dist-packages (from requests<3.0.0,>=2.25.1->pwncat-cs) (2020.6.20)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in /usr/lib/python3/dist-packages (from requests<3.0.0,>=2.25.1->pwncat-cs) (1.26.5)
Requirement already satisfied: idna<4,>=2.5 in /usr/lib/python3/dist-packages (from requests<3.0.0,>=2.25.1->pwncat-cs) (3.3)
Requirement already satisfied: charset-normalizer<4,>=2 in ./.local/lib/python3.10/site-packages (from requests<3.0.0,>=2.25.1->pwncat-cs) (3.0.1)
Collecting commonmark<0.10.0,>=0.9.0
  Downloading commonmark-0.9.1-py2.py3-none-any.whl (51 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 51.1/51.1 KB 4.1 MB/s eta 0:00:00
Requirement already satisfied: pygments<3.0.0,>=2.6.0 in /usr/lib/python3/dist-packages (from rich<11.0.0,>=10.4.0->pwncat-cs) (2.11.2)
Requirement already satisfied: colorama<0.5.0,>=0.4.0 in /usr/lib/python3/dist-packages (from rich<11.0.0,>=10.4.0->pwncat-cs) (0.4.4)
Collecting BTrees>=4.0.0dev
  Downloading BTrees-5.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (3.7 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 3.7/3.7 MB 4.4 MB/s eta 0:00:00
Collecting ZEO>=4.0.0dev
  Downloading ZEO-6.0.0-py3-none-any.whl (247 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 247.2/247.2 KB 3.4 MB/s eta 0:00:00
Collecting ZODB>=4.0.0dev
  Downloading ZODB-5.8.1-py2.py3-none-any.whl (422 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 422.3/422.3 KB 3.9 MB/s eta 0:00:00
Collecting persistent>=4.0.0dev
  Downloading persistent-5.2-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl (231 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 231.4/231.4 KB 3.8 MB/s eta 0:00:00
Collecting transaction
  Downloading transaction-4.0-py3-none-any.whl (46 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 46.6/46.6 KB 2.7 MB/s eta 0:00:00
Collecting ZConfig
  Downloading ZConfig-4.0-py3-none-any.whl (131 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 131.5/131.5 KB 3.3 MB/s eta 0:00:00
Requirement already satisfied: zope.interface>=5.0.0 in ./.local/lib/python3.10/site-packages (from BTrees>=4.0.0dev->ZODB3<4.0.0,>=3.11.0->pwncat-cs) (6.1)
Requirement already satisfied: pycparser in /usr/local/lib/python3.10/dist-packages (from cffi>=1.4.1->PyNaCl<2.0.0,>=1.4.0->pwncat-cs) (2.21)
Collecting zdaemon
  Downloading zdaemon-5.0-py3-none-any.whl (56 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 56.0/56.0 KB 4.3 MB/s eta 0:00:00
Collecting zc.lockfile
  Downloading zc.lockfile-3.0.post1-py3-none-any.whl (9.8 kB)
Collecting zodbpickle>=1.0.1
  Downloading zodbpickle-3.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (283 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 283.7/283.7 KB 3.7 MB/s eta 0:00:00
Requirement already satisfied: six in /usr/lib/python3/dist-packages (from ZODB>=4.0.0dev->ZODB3<4.0.0,>=3.11.0->pwncat-cs) (1.16.0)
Requirement already satisfied: setuptools in /usr/lib/python3/dist-packages (from zodbpickle>=1.0.1->ZODB>=4.0.0dev->ZODB3<4.0.0,>=3.11.0->pwncat-cs) (59.6.0)
Building wheels for collected packages: ZODB3
  Building wheel for ZODB3 (setup.py) ... done
  Created wheel for ZODB3: filename=ZODB3-3.11.0-py3-none-any.whl size=1829 sha256=6955f5d364661f4a563e51d5e260d49063eb4d08f7143e930dea98c3e20d216c
  Stored in directory: /home/olej/.cache/pip/wheels/2f/e2/54/02b429a8f1c070530f7465ac75c0b39dc89319d311f5db3493
Successfully built ZODB3
Installing collected packages: commonmark, zodbpickle, ZConfig, zc.lockfile, rich, python-rapidjson, packaging, bcrypt, zdaemon, transaction, persistent, paramiko-ng, BTrees, ZODB, ZEO, zodburi, ZODB3, pwncat-cs
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
poetry 1.1.12 requires keyring<22.0.0,>=21.2.0; python_version >= "3.6" and python_version < "4.0", but you have keyring 23.5.0 which is incompatible.
Successfully installed BTrees-5.2 ZConfig-4.0 ZEO-6.0.0 ZODB-5.8.1 ZODB3-3.11.0 bcrypt-4.1.2 commonmark-0.9.1 packaging-20.9 paramiko-ng-2.8.10 persistent-5.2 pwncat-cs-0.5.4 python-rapidjson-1.16 rich-10.16.2 transaction-4.0 zc.lockfile-3.0.post1 zdaemon-5.0 zodbpickle-3.2 zodburi-2.6.0
Устанавливается он локально, в пользовательский каталог:

Код: Выделить всё

olej@R420:~$ which pwncat-cs
/home/olej/.local/bin/pwncat-cs

Код: Выделить всё

olej@R420:~$ ls -o `which pwncat-cs`
-rwxrwxr-x 1 olej 214 мар 12 11:35 /home/olej/.local/bin/pwncat-cs

Код: Выделить всё

olej@R420:~$ pwncat-cs --help
usage: pwncat-cs [-h] [--version] [--download-plugins] [--config CONFIG] [--ssl] [--ssl-cert SSL_CERT] [--ssl-key SSL_KEY]
                 [--identity IDENTITY] [--listen] [--platform PLATFORM] [--port PORT] [--list] [--verbose]
                 [[protocol://][user[:password]@][host][:port]] [port]

Start interactive pwncat session and optionally connect to existing victim via a known platform and channel type. This entrypoint can
also be used to list known implants on previous targets.

positional arguments:
  [protocol://][user[:password]@][host][:port]
                        Connection string describing victim
  port                  Alternative port number to support netcat-style syntax

options:
  -h, --help            show this help message and exit
  --version, -v         Show version number and exit
  --download-plugins    Pre-download all Windows builtin plugins and exit immediately
  --config CONFIG, -c CONFIG
                        Custom configuration file (default: ./pwncatrc)
  --ssl                 Connect or listen with SSL
  --ssl-cert SSL_CERT   Certificate for SSL-encrypted listeners (PEM)
  --ssl-key SSL_KEY     Key for SSL-encrypted listeners (PEM)
  --identity IDENTITY, -i IDENTITY
                        Private key for SSH authentication
  --listen, -l          Enable the `bind` protocol (supports netcat-style syntax)
  --platform PLATFORM, -m PLATFORM
                        Name of the platform to use (default: linux)
  --port PORT, -p PORT  Alternative way to specify port to support netcat-style syntax
  --list                List installed implants with remote connection capability
  --verbose, -V         Enable verbose output for the remote commands executed by `pwncat`

Ответить

Вернуться в «Сеть, сетевые службы и сервисы»

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и 2 гостя