Быстрый TCP/UDP туннель через HTTP с шифрованием SSH, поддерживающий обратное перенаправление портов, прокси SOCKS5 и аутентификацию клиентов для безопасного обхода сети и обхода брандмауэров.
Chisel — это быстрый TCP/UDP-туннель, передаваемый через HTTP и защищённый через SSH. Один исполняемый файл включает и клиент, и сервер. Написан на Go (golang). Chisel в основном полезен для обхода межсетевых экранов, но также может использоваться для предоставления защищённой конечной точки в вашу сеть.

crypto/ssh)--min/max-retry-interval); keepalive-пинги имеют тайм-аут, поэтому молча оборванные соединения (сон/пробуждение, тайм-ауты NAT, перезапуски сервера) обнаруживаются и восстанавливаютсяssh -o ProxyCommand, обеспечивая SSH через HTTPСм. последний релиз или скачайте и установите его сейчас с помощью curl https://i.jpillora.com/chisel! | bash
Бинарные файлы собираются с последней версией Go, которая задаёт минимальные версии ОС: Windows 10 / Server 2016, macOS 12, ядро Linux 3.2, FreeBSD 12.2. Для более старых систем (например, Windows 7) используйте релиз v1.8.1 или более ранние.
Изображения являются мультиархитектурными и публикуются как в Docker Hub (`jpillora/chisel`), так и в GitHub Container Registry (`ghcr.io/jpillora/chisel`).
### Fedora
Пакет поддерживается сообществом Fedora. Если вы столкнулись с проблемами, связанными с использованием RPM, пожалуйста, воспользуйтесь этим [трекером проблем](https://bugzilla.redhat.com/buglist.cgi?bug_status=NEW&bug_status=ASSIGNED&classification=Fedora&component=chisel&list_id=11614537&product=Fedora&product=Fedora%20EPEL).```sh
sudo dnf -y install chisel
$ go install github.com/jpillora/chisel@latest
## Демо
Вы можете запустить собственный демо-сервер за считанные минуты (старое демо на Heroku исчезло вместе с бесплатным тарифом Heroku). [`example/fly.toml`](https://github.com/jpillora/chisel/blob/HEAD/example/fly.toml) разворачивает этот `chisel server` на бесплатном лимите [fly.io](https://fly.io):```sh
$ chisel server --port $PORT --backend http://example.com
# listens on $PORT, proxies normal web requests to http://example.com
Разверните его с помощью fly launch --copy-config из каталога example/, затем создайте туннель к любому сервису, работающему рядом с сервером, например:```sh
$ chisel client https://.fly.dev 3000
Посещение URL вашего приложения в браузере обращается к прокси-серверу бэкенда по умолчанию и показывает копию [example.com](http://example.com).
## Использование
<!-- отображайте эти тексты справки вручную,
или используйте https://github.com/jpillora/md-tmpl
с $ md-tmpl -w README.md -->
<!--tmpl,code=plain:echo "$ chisel --help" && go run main.go --help | sed 's#0.0.0-src (go1\..*)#X.Y.Z#' -->``` plain
$ chisel --help
Usage: chisel [command] [--help]
Version: X.Y.Z
Commands:
server - runs chisel in server mode
client - runs chisel in client mode
Read more:
https://github.com/jpillora/chisel
$ chisel server --help
Usage: chisel server [options]
Options:
--host, Defines the HTTP listening host – the network interface
(defaults the environment variable HOST and falls back to 0.0.0.0).
--port, -p, Defines the HTTP listening port (defaults to the environment
variable PORT and falls back to port 8080).
--key, (deprecated use --keygen and --keyfile instead)
An optional string to seed the generation of a ECDSA public
and private key pair. All communications will be secured using this
key pair. Share the subsequent fingerprint with clients to enable detection
of man-in-the-middle attacks (defaults to the CHISEL_KEY environment
variable, otherwise a new key is generate each run).
--keygen, A path to write a newly generated PEM-encoded SSH private key file.
If users depend on your --key fingerprint, you may also include your --key to
output your existing key. Use - (dash) to output the generated key to stdout.
--keyfile, An optional path to a PEM-encoded SSH private key. When
this flag is set, the --key option is ignored, and the provided private key
is used to secure all communications. (defaults to the CHISEL_KEY_FILE
environment variable). Since ECDSA keys are short, you may also set keyfile
to the inline key string itself, exactly as printed by --keygen (a base64
string with a "ck-" prefix); no extra base64 encoding is needed.
--authfile, An optional path to a users.json file. This file should
be an object with users defined like:
{
"<user:pass>": ["<addr-regex>","<addr-regex>"]
}
when <user> connects, their <pass> will be verified and then
each of the remote addresses will be compared against the list
of address regular expressions for a match. Patterns are NOT
anchored by default: "10.0.0.1:80" also matches
"210.0.0.1:8080", and "." matches any character. Anchor your
patterns, e.g. "^10\.0\.0\.1:80$". The empty string ""
matches every address. Addresses will
always come in the form "<remote-host>:<remote-port>" for normal remotes,
"R:<local-interface>:<local-port>" for reverse port forwarding
remotes, and "socks" for SOCKS5 proxy access. Note that SOCKS5
access previously bypassed this list; existing authfiles which
should allow SOCKS5 must add an entry matching "socks" (the
empty wildcard "" matches everything, including "socks"). This
file will be automatically reloaded on change. Reloads apply
to new connections and to new tunnels of connected clients;
established tunnels are not interrupted.
--auth, An optional string representing a single user with full
access, in the form of <user:pass>. It is equivalent to creating an
authfile with {"<user:pass>": [""]}. If unset, it will use the
environment variable AUTH.
--keepalive, An optional keepalive interval. Since the underlying
transport is HTTP, in many instances we'll be traversing through
proxies, often these proxies will close idle connections. You must
specify a time with a unit, for example '5s' or '2m'. Defaults
to '25s' (set to 0s to disable).
--backend, Specifies another HTTP server to proxy requests to when
chisel receives a normal HTTP request. Useful for hiding chisel in
plain sight. --proxy is accepted as an alias for this flag.
--socks5, Allow clients to access the internal SOCKS5 proxy. See
chisel client --help for more information.
--reverse, Allow clients to specify reverse port forwarding remotes
in addition to normal remotes.
--tls-key, Enables TLS and provides optional path to a PEM-encoded
TLS private key. When this flag is set, you must also set --tls-cert,
and you cannot set --tls-domain.
--tls-cert, Enables TLS and provides optional path to a PEM-encoded
TLS certificate. When this flag is set, you must also set --tls-key,
and you cannot set --tls-domain.
--tls-domain, Enables TLS and automatically acquires a TLS key and
certificate using LetsEncrypt. Setting --tls-domain requires port 443.
You may specify multiple --tls-domain flags to serve multiple domains.
The resulting files are cached in the "$HOME/.cache/chisel" directory.
You can modify this path by setting the CHISEL_LE_CACHE variable,
or disable caching by setting this variable to "-". You can optionally
provide a certificate notification email by setting CHISEL_LE_EMAIL.
--tls-ca, a path to a PEM encoded CA certificate bundle or a directory
holding multiple PEM encode CA certificate bundle files, which is used to
validate client connections. The provided CA certificates will be used
instead of the system roots. This is commonly used to implement mutual-TLS.
--pid Generate pid file in current working directory
-v, Enable verbose logging
--help, This help text
Signals: The chisel process is listening for: a SIGINT or SIGTERM to begin a graceful shutdown (a second signal forces an immediate exit), a SIGUSR2 to print process stats, and a SIGHUP to short-circuit the client reconnect timer
Version: X.Y.Z
Read more: https://github.com/jpillora/chisel
<!--/tmpl-->
<!--tmpl,code=plain:echo "$ chisel client --help" && go run main.go client --help | sed 's#0.0.0-src (go1\..*)#X.Y.Z#' -->``` plain
$ chisel client --help
Usage: chisel client [options] <server> <remote> [remote] [remote] ...
<server> is the URL to the chisel server.
<remote>s are remote connections tunneled through the server, each of
which come in the form:
<local-host>:<local-port>:<remote-host>:<remote-port>/<protocol>
■ local-host defaults to 0.0.0.0 (all interfaces).
■ local-port defaults to remote-port.
■ remote-port is required*.
■ remote-host defaults to 127.0.0.1 (server localhost).
■ protocol defaults to tcp.
which shares <remote-host>:<remote-port> from the server to the client
as <local-host>:<local-port>, or:
R:<local-interface>:<local-port>:<remote-host>:<remote-port>/<protocol>
which does reverse port forwarding, sharing <remote-host>:<remote-port>
from the client to the server's <local-interface>:<local-port>.
example remotes
3000
example.com:3000
3000:google.com:80
192.168.0.5:3000:google.com:80
socks
5000:socks
R:2222:localhost:22
R:socks
R:5000:socks
stdio:example.com:22
1.1.1.1:53/udp
When the chisel server has --socks5 enabled, remotes can
specify "socks" in place of remote-host and remote-port.
The default local host and port for a "socks" remote is
127.0.0.1:1080. Connections to this remote will terminate
at the server's internal SOCKS5 proxy. When the server also
has --authfile set, SOCKS5 access requires an entry matching
the token "socks" in the user's address list.
When the chisel server has --reverse enabled, remotes can
be prefixed with R to denote that they are reversed. That
is, the server will listen and accept connections, and they
will be proxied through the client which specified the remote.
Reverse remotes specifying "R:socks" will listen on the server's
default socks port (1080) and terminate the connection at the
client's internal SOCKS5 proxy.
When stdio is used as local-host, the tunnel will connect standard
input/output of this program with the remote. This is useful when
combined with ssh ProxyCommand. You can use
ssh -o ProxyCommand='chisel client chiselserver stdio:%h:%p' \
[email protected]
to connect to an SSH server through the tunnel.
Options:
--fingerprint, A *strongly recommended* fingerprint string
to perform host-key validation against the server's public key.
Fingerprint mismatches will close the connection.
Fingerprints are generated by hashing the ECDSA public key using
SHA256 and encoding the result in base64.
Fingerprints must be 44 characters containing a trailing equals (=).
Legacy MD5 colon fingerprints (deprecated) are still accepted,
but only in their full 16-octet form; truncated prefixes are
rejected.
--auth, An optional username and password (client authentication)
in the form: "<user>:<pass>". These credentials are compared to
the credentials inside the server's --authfile. defaults to the
AUTH environment variable.
--keepalive, An optional keepalive interval. Since the underlying
transport is HTTP, in many instances we'll be traversing through
proxies, often these proxies will close idle connections. You must
specify a time with a unit, for example '5s' or '2m'. Defaults
to '25s' (set to 0s to disable).
--max-retry-count, Maximum number of times to retry before exiting.
Defaults to unlimited.
--min-retry-interval, Minimum wait time before retrying after a
disconnection. Defaults to 1 second.
--max-retry-interval, Maximum wait time before retrying after a
disconnection. Defaults to 5 minutes.
--proxy, An optional HTTP CONNECT or SOCKS5 proxy which will be
used to reach the chisel server. Authentication can be specified
inside the URL. Credentials must be URL-encoded; for example a
"#" in the password must be written as "%23".
For example, http://admin:[email protected]:8081
or: socks://admin:[email protected]:1080
The socks://, socks5:// and socks5h:// schemes are equivalent:
DNS is always resolved by the proxy.
--header, Set a custom header in the form "HeaderName: HeaderContent".
Can be used multiple times. (e.g --header "Foo: Bar" --header "Hello: World")
--hostname, Optionally set the 'Host' header (defaults to the host
found in the server url).
--sni, Override the ServerName when using TLS (defaults to the
hostname).
--tls-ca, An optional root certificate bundle used to verify the
chisel server. Only valid when connecting to the server with
"https" or "wss". By default, the operating system CAs will be used.
--tls-skip-verify, Skip server TLS certificate verification of
chain and host name (if TLS is used for transport connections to
server). If set, client accepts any TLS certificate presented by
the server and any host name in that certificate. This only affects
transport https (wss) connection. Chisel server's public key
may be still verified (see --fingerprint) after inner connection
is established.
--tls-key, a path to a PEM encoded private key used for client
authentication (mutual-TLS).
--tls-cert, a path to a PEM encoded certificate matching the provided
private key. The certificate must have client authentication
enabled (mutual-TLS).
--pid Generate pid file in current working directory
-v, Enable verbose logging
--help, This help text
Signals:
The chisel process is listening for:
a SIGINT or SIGTERM to begin a graceful shutdown
(a second signal forces an immediate exit),
a SIGUSR2 to print process stats, and
a SIGHUP to short-circuit the client reconnect timer
Version:
X.Y.Z
Read more:
https://github.com/jpillora/chisel
Шифрование включено всегда. При запуске сервера chisel генерируется пара ключей ECDSA (открытый/закрытый) в памяти. Отпечаток открытого ключа (base64-кодированный SHA256) отображается при запуске сервера. Вместо генерации случайного ключа сервер может указать файл ключа с помощью опции --keyfile. При подключении клиенты также отображают отпечаток открытого ключа сервера. Клиент может принудительно задать конкретный отпечаток с помощью опции --fingerprint. Устаревшие MD5-отпечатки по-прежнему принимаются, но должны быть в полной 16-октетной форме через двоеточие — усечённые префиксы отклоняются. Дополнительную информацию см. в --help выше.
Сервер также ограничивает размер входящих websocket-сообщений до аутентификации (CHISEL_WS_READ_LIMIT, по умолчанию 512 КиБ), поэтому неаутентифицированные пиры не могут исчерпать память сообщениями чрезмерного размера. Значение по умолчанию с запасом превышает максимальный транспортный пакет SSH в 256 КиБ из x/crypto/ssh, поэтому ни один корректный SSH-пакет никогда не отклоняется. Только 0 отключает ограничение; отрицательные значения возвращаются к безопасному значению по умолчанию.
С помощью опции --authfile сервер может предоставить файл конфигурации user.json для создания списка принимаемых пользователей. Клиент затем аутентифицируется с помощью опции --auth. Пример файла конфигурации аутентификации см. в users.json. Дополнительную информацию см. в --help выше.
Примечания о поведении authfile:
^ и $ (сервер предупреждает о незакреплённых шаблонах при загрузке). Пустая строка "" соответствует всему.socks. Критическое изменение: ранее SOCKS5 полностью обходил authfile; серверы, работающие с --socks5 и --authfile, должны предоставить socks пользователям, которым нужен прокси-доступ (записи с подстановочным знаком "" продолжают работать).user:pass) теперь являются фатальной ошибкой запуска и на сервере, и на клиенте — ранее они молча отключали аутентификацию.--auth переживает перезагрузки authfile и выигрывает конфликты имён с пользователями из файла.Внутренне это реализуется с помощью метода аутентификации Password, предоставляемого SSH. Подробнее о crypto/ssh см. здесь http://blog.gopheracademy.com/go-and-ssh/. Открытие/закрытие сессий (с пользователем, исходным адресом и remotes) и неудачные попытки входа регистрируются на уровне info.
Самая простая безопасная настройка — --tls-domain, которая автоматически предоставляет сертификат LetsEncrypt (требуется порт 443 и DNS-запись, указывающая на сервер):```sh
chisel server --port 443 --tls-domain chisel.example.com --auth user:pass
chisel client --auth user:pass https://chisel.example.com R:2222:localhost:22
Чтобы использовать собственный сертификат (самоподписанный или внутреннего ЦС), сгенерируйте пару ключ/сертификат и укажите обеим сторонам на соответствующие файлы:```sh
chisel server --port 443 --tls-key key.pem --tls-cert cert.pem
chisel client --tls-ca ca.pem https://chisel.example.com 3000
Для взаимного TLS также передайте --tls-ca серверу и --tls-cert/--tls-key каждому клиенту. Обратите внимание, что TLS оборачивает транспорт chisel снаружи; внутренний уровень SSH по-прежнему шифрует и аутентифицирует, поэтому проверка --fingerprint работает как с TLS, так и без него.
Выведите новый закрытый ключ в терминал
chisel server --keygen -
# или сохраните его на диск --keygen /path/to/mykey
Запустите ваш chisel-сервер
jpillora/chisel server --keyfile '<ck-base64 строка или путь к файлу>' -p 9312 --socks5
Подключите ваш chisel-клиент (используя отпечаток сервера)
chisel client --fingerprint '<см. вывод сервера>' <server-address>:9312 socks
Направьте ваши SOCKS5-клиенты (например, ОС/браузер) на:
<client-address>:1080
Теперь у вас есть зашифрованное и аутентифицированное SOCKS5-соединение через HTTP
Примечание: если сервер также использует --authfile, пользователям нужна запись, соответствующая токену socks, чтобы использовать прокси (см. Аутентификация).
Чтобы позволить конкретному клиенту действовать как SOCKS-выходной узел, предоставьте ему адрес прослушивания обратного SOCKS (R:socks прослушивает 127.0.0.1:1080 на сервере):```json
{
"exituser:password": ["^R:127\.0\.0\.1:1080$"]
}
I need the input content to translate. Please provide the chunk of Markdown content you'd like me to translate from English to Russian.```sh
chisel server --reverse --authfile users.json
chisel client --auth exituser:password <server-address> R:socks
# server-side consumers point SOCKS5 clients at 127.0.0.1:1080,
# and their traffic exits via the chisel client's network
См. также пошаговый пример обратного туннелирования.
chisel работает через CDN, поддерживающие WebSockets. Для Cloudflare: включите WebSockets, проксируйте (оранжевое облако) DNS-запись и подключайте клиентов через https://. CDN завершает TLS, но внутренний SSH-слой означает, что проверка --fingerprint по-прежнему аутентифицирует ваш сервер chisel сквозным образом — CDN не может читать или изменять туннелируемый трафик. Оставьте --keepalive на значении по умолчанию 25s, чтобы не превышать таймауты простоя CDN, и учтите, что прокси, удаляющие заголовки Upgrade, вообще не могут передавать chisel.
Менее распространённые параметры задаются переменными окружения, все они читаются с префиксом CHISEL_ (например, CHISEL_WS_TIMEOUT=10s):
| Переменная | Сторона | По умолчанию | Назначение |
|---|---|---|---|
WS_TIMEOUT | клиент | 45s | таймаут рукопожатия websocket |
SSH_TIMEOUT | клиент | 30s | таймаут рукопожатия ssh |
CONFIG_TIMEOUT | сервер | 10s | ожидание запроса конфигурации от клиента |
SSH_WAIT | обе | 35s | как долго новые туннели ждут активного соединения |
PING_TIMEOUT | обе | интервал keepalive | таймаут ответа на keepalive-пинг (без пингов при --keepalive 0) |
DIAL_TIMEOUT | выходной узел | 30s | таймаут tcp-подключения к целям туннеля |
WS_READ_LIMIT | обе | 524288 | максимальный размер входящего websocket-сообщения в байтах (0 = без лимита; отрицательное = по умолчанию) |
WS_BUFF_SIZE | обе | по умолчанию Go | размеры буферов чтения/записи websocket |
UDP_MAX_SIZE | обе | 9012 | максимальный размер udp-пакета в байтах |
UDP_DEADLINE | выходной узел | 15s | дедлайн чтения udp-потока и возраст очистки простоя |
UDP_MAX_CONNS | выходной узел | 100 | максимум одновременных udp-потоков на туннель |
SHUTDOWN_GRACE | сервер | 5s | время слива http-запросов при завершении работы |
HOST, PORT, AUTH и CHISEL_KEY/CHISEL_KEY_FILE описаны в текстах --help выше.
Поскольку требуется поддержка WebSockets:
github.com/jpillora/chisel/share содержит общий пакетgithub.com/jpillora/chisel/server содержит пакет сервераgithub.com/jpillora/chisel/client содержит пакет клиента1.0 — Первоначальный выпуск1.1 — Заменено простое симметричное шифрование на ECDSA SSH1.2 — Добавлена поддержка SOCKS5 (сервер) и HTTP CONNECT (клиент)1.3 — Добавлена поддержка обратного туннелирования1.4 — Добавлена поддержка произвольных HTTP-заголовков1.5 — Добавлена поддержка обратного SOCKS (от @aus)1.6 — Добавлена поддержка stdio клиента (от @BoleynSu)1.7 — Добавлена поддержка UDP1.8 — Переход на Docker-образ scratch1.9 — Обновление до Go 1.21. Переход с сида --key на строки P256-ключей с помощью --key{gen,file} (от @cmenginnz)1.10 — Обновление до Go 1.22. Добавлены .rpm, .deb и .apk в релизы. Исправлено некорректное сравнение версий.1.11 — Обновление до Go 1.25.1. Обновлены все зависимости.1.12 — Проход по надёжности и безопасности:
CHISEL_PING_TIMEOUT), поэтому мёртвые соединения быстро переподключаются после сна/пробуждения, таймаутов NAT и перезапусков сервера--socks5 + --authfile доступ к SOCKS5 теперь требует запись в authfile, соответствующую socks (записи с подстановочным "" продолжают работать)--fingerprint должен быть полной SHA256-формой (или полной 16-октетной MD5-формой с двоеточиями)--auth user) вызывают фатальную ошибку при запуске вместо молчаливого отключения аутентификацииCHISEL_DIAL_TIMEOUT, по умолчанию 30s)CHISEL_SHUTDOWN_GRACE); второй сигнал принудительно завершает процессЧетыре изменения могут потребовать действий при обновлении с 1.11.x или более ранних версий:
--authfile (принудительно с v1.11.7): пользователям, которым нужен прокси-доступ, требуется запись в authfile, соответствующая токену socks (подстановочный "" продолжает работать). См. Аутентификация. Отклонённые запросы логируются на стороне сервера как Denied connection to socks (ACL).--fingerprint: усечённые устаревшие MD5-отпечатки отклоняются. Используйте полный SHA256-отпечаток, выводимый сервером и клиентом (полная 16-октетная MD5-форма с двоеточиями по-прежнему принимается, но устарела).--auth должны быть <user>:<pass> — строки без двоеточия теперь вызывают ошибку при запуске вместо молчаливого отключения аутентификации.chisel client с --max-retry-count теперь завершается с ненулевым кодом, когда попытки соединения исчерпаны; скрипты, проверяющие $?, и юниты systemd с Restart=on-failure это заметят.MIT © Jaime Pillora
CHISEL_UDP_MAX_CONNS)CHISEL_WS_READ_LIMIT)--max-retry-count; новый --min-retry-interval (по умолчанию 1s); socks5:// принимается для --proxygo install сообщают свою реальную версию; сеансы и неудачные входы логируются на уровне infox/crypto/ssh обновлён до v0.55.0 для устранения GO-2026-6303latest / X / X.Y