Compare commits

..
20 Commits
Author SHA1 Message Date
Vladimir Dubrovin 3f65105637 dnspr: a name server's answer with no records relayed as it is (#1292)
C/C++ CI Linux / ubuntu-24.04-arm (push) Waiting to run
C/C++ CI Linux / ubuntu-latest (push) Waiting to run
C/C++ CI MacOS / macos-15 (push) Waiting to run
C/C++ CI Windows / windows-2022 (push) Waiting to run
C/C++ CI cmake / macos-15 (push) Waiting to run
C/C++ CI cmake / ubuntu-24.04-arm (push) Waiting to run
C/C++ CI cmake / ubuntu-latest (push) Waiting to run
C/C++ CI cmake / windows-2022 (push) Waiting to run
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Waiting to run
2026-11-26 15:50:12 +03:00
Vladimir Dubrovin 0d2554614d tlspr: the SNI break split sent once the destination is connected 2026-11-26 15:39:07 +03:00
github-actions[bot] d323ab2d5a Update HTML documentation from man pages
C/C++ CI Linux / ubuntu-24.04-arm (push) Canceled after 0s
C/C++ CI Linux / ubuntu-latest (push) Canceled after 0s
C/C++ CI cmake / macos-15 (push) Canceled after 0s
C/C++ CI cmake / ubuntu-24.04-arm (push) Canceled after 0s
C/C++ CI cmake / ubuntu-latest (push) Canceled after 0s
C/C++ CI cmake / windows-2022 (push) Canceled after 0s
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Canceled after 0s
Update version files / version (push) Canceled after 0s
C/C++ CI Windows / windows-2022 (push) Canceled after 0s
Update wiki / wiki (push) Canceled after 0s
C/C++ CI MacOS / macos-15 (push) Canceled after 0s
Update HTML documentation / docs (push) Canceled after 0s
2026-11-21 11:46:20 +00:00
Vladimir Dubrovin 570cbe307b Merge branch 'master' of https://github.com/3proxy/3proxy 2026-11-21 14:45:53 +03:00
Vladimir Dubrovin ca70026d27 radius: a server may be a name, and the port is taken as written (#1027)
The port was promised by the man page but never parsed: a server
address with a port was refused, and only the default 1812 could be
used. The address is parsed with parsehost() now, as nserver and
authnserver are, so a name is resolved when the configuration is read,
an IPv6 address may be written in brackets, and the port is the one
authentication is asked on, the accounting of the same server going to
the port after it. The man page says which name servers resolve the
name.
2026-11-21 14:44:50 +03:00
github-actions[bot] 7ad964d6e8 Update HTML documentation from man pages 2026-11-21 11:25:06 +00:00
Vladimir Dubrovin 31438b7c90 resolve: a name server answering with an error asks the next one (#735)
A reply with no answers and an error code - FORMERR, SERVFAIL, NOTIMP,
REFUSED - ended the resolution as if the name had no address, and the
servers after the one that answered were never asked, so one broken
server made every name it broke fail. Such an answer is passed over for
the next server now; a reply without data, and one that says the name is
not there, still end the search.
2026-11-21 13:59:15 +03:00
github-actions[bot] e28d86d7e4 Update version files for 1.0.4 2026-11-21 09:08:54 +00:00
Vladimir Dubrovin 7da58510d0 Commit as 1.0.4 2026-11-21 12:08:39 +03:00
Vladimir Dubrovin 8b298657ce socks: a SOCKS4a request is not a connect to the null address
C/C++ CI Linux / ubuntu-24.04-arm (push) Canceled after 0s
C/C++ CI Linux / ubuntu-latest (push) Canceled after 0s
C/C++ CI MacOS / macos-15 (push) Canceled after 0s
C/C++ CI Windows / windows-2022 (push) Canceled after 0s
C/C++ CI cmake / macos-15 (push) Canceled after 0s
C/C++ CI cmake / ubuntu-24.04-arm (push) Canceled after 0s
C/C++ CI cmake / ubuntu-latest (push) Canceled after 0s
C/C++ CI cmake / windows-2022 (push) Canceled after 0s
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Canceled after 0s
2026-11-18 21:37:33 +03:00
Vladimir Dubrovin 84f6ee6ce4 auth: the pre-authorization of a UDP ASSOCIATE is not cached 2026-11-18 20:43:59 +03:00
Vladimir Dubrovin 37eaa4f2a9 socks: a UDP association is not relayed direct when its parent fails 2026-11-18 20:43:58 +03:00
Vladimir Dubrovin 46297ecf7e socks: a host name with control bytes or spaces is refused where it is read 2026-11-18 20:43:58 +03:00
Vladimir Dubrovin 734c968030 smtpp: a login name of a port alone names no destination 2026-11-18 20:43:58 +03:00
Vladimir Dubrovin 5babf687f6 proxy: credentials of an earlier request not inherited by the next
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Has been cancelled
2026-11-13 17:38:47 +03:00
Vladimir Dubrovin 3894d25a02 httpsrv: credentials of an earlier request not inherited by the next 2026-11-13 17:14:36 +03:00
Vladimir Dubrovin 9a2351abeb tlspr: a ServerHello too short for the extensions length refused (#1286)
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Has been cancelled
2026-11-10 15:20:08 +03:00
Vladimir Dubrovin 99e72a1417 httpsrv: a limit exceeded answered with 503, not ignored
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Has been cancelled
Authorization reports 10 when a limit of the service was exceeded,
which every other child answers with 503; the http server took it as
success and answered the request anyway. It now says 503 for itself,
after the body of the request is drained as any answer here does.

(cherry picked from commit 5a2e9d27c3)
2026-11-08 14:40:00 +03:00
Vladimir Dubrovin 9d2616e8ba httpsrv: a dot-dot segment of a path refused, with either separator
A path ending in a backslashed dot-dot, or carrying one in a form the
checks did not name, was taken as it stood. Any dot-dot segment is now
refused wherever it is and whichever separator carries it, and a path
ending in a bare dot of either kind.

(cherry picked from commit c0eb7a65c6)
2026-11-08 14:40:00 +03:00
Vladimir Dubrovin 78385588ec pcre: a rule with no ACL a match data of its own, not itself
A rule whose ACL was missing was handed to the filters as the
connection's data, which they read as a match data block and freed:
a pointer into the configuration, dereferenced as another type and
given back to malloc. A rule without an ACL now skips the check and
goes on with a block of its own, and nothing a filter is given is
ever the rule itself.

(cherry picked from commit a7e5a8b48b)
2026-11-08 14:40:00 +03:00
29 changed files with 676 additions and 66 deletions

No files matched your search

+12 -12
View File
@@ -1,13 +1,13 @@
3proxy-1.0.3 Released November, 7 2026
3proxy-1.0.4 Released November, 21 2026
! Fix: RADIUS authentication: the reply digest copied the shared secret right after the received bytes, so a reply of 4100 bytes with a secret of 17 or more characters wrote up to 47 bytes of it past the reply buffer on the stack, before the reply was authenticated; the digest is hashed over the reply and the secret in place now, with nothing written past the reply, and a reply is taken only from the address and port of the server the request went to, with the request's identifier and length, which was never checked before
! Fix: the PTR answer of a name server could write past the answer buffer on the stack: the label walk ran to the end of the whole message instead of the end of the record's data and could take a compression pointer for a label length (an answer of 3841 bytes or more reached past the buffer itself); the walk now stops at the end of the record's data, and a compressed, empty or truncated name is not accepted
! Fix: every connection matching a pcre: (or regex:) rule matched on the one match data block of the rule, which pcre2_match() writes into: two connections matching at the same time raced and corrupted memory, bringing the process down under load; a connection now makes a match data block of its own
! Fix: TLS: a read which could only be done once a write was, or a write once a read was (a TLS 1.3 key update answered while the socket cannot take more, for example), ended the connection with an error; each TLS socket remembers now what its pending read and write wait for, and the poll of the TLS layer waits for that
! Fix: Windows: a TLS read or write which wanted the socket again was not seen as one and dropped the connection with an unrelated error: the C library's errno was set where the socket error is read
! Fix: a client of a connect back (-R) service stayed in accept() for the connection another client of the same service took, until the next one came, past its time out and through a configuration reload; the connect back socket is non-blocking now, and an accept() with nothing to take does not count as one of the client's tries
! Fix: ftppr: the answer of a server which logs in on USER alone (230, as anonymous FTP often does) or refuses the login was read but never handed to the client, which was left waiting for the answer to its PASS until the time out (#1284)
! Fix: plugins: StringsPlugin, cutting a string table line at its end, wrote NULs past the line, into what the buffer kept of longer lines read before or past its end; FilePlugin passed the TLS state of the connection where the client's parameters were expected, so sending a string table over a TLS connection read a TLS state as a clientparam
+ -B (for TCP services) splits the TLS ClientHello passed through tlspr in the middle of the server name (SNI), so DPI systems which do not reassemble it do not see the host name; TCP_NODELAY, set by default, must not be turned off, or the kernel may join the segments again; -s keeps the same effect where -s is not splice (#1283)
+ 3proxy --help (and the usage message of a bad invocation) lists what the build was made with: TLS and its backend, RADIUS, PCRE, IPv6, UNIX sockets, the built-in HTTP server, transparency, ODBC and the optional proxy services
+ An outgoing connection bound to an external address is bound with IP_BIND_ADDRESS_NO_PORT on Linux 4.2 and later: the port is chosen by connect() for the pair with the destination, so ports in use towards other destinations or closing in TIME_WAIT do not run the ephemeral range out; bind() no longer failed with result 12 or searched long for a port under many connections
! Fix: socks: a SOCKS4a request was refused as a connect to the null address, although in SOCKS4a the null address means that the destination is the name which follows it
! Fix: auth: a UDP ASSOCIATE is pre-authorized without looking at the destination its rules depend on, so its verdict holds for that association alone and is not kept for later requests
! Fix: socks: a UDP association was relayed direct when its parent failed, although the rules demanded the parent; it is refused now
! Fix: socks: a host name with control bytes or spaces in it was taken as it stood; it is refused where it is read now
! Fix: smtpp: a login name of a port alone, without a host, set the port but named no destination to connect to; such a login is refused now
! Fix: proxy: the credentials of an earlier request on a kept-alive connection decided for the requests after it; every request is authorized by its own credentials now
! Fix: the built-in http server (httpsrv): the credentials of an earlier request on a kept-alive connection decided for the requests after it; every request is authorized by its own credentials now
! Fix: tlspr: a TLS ServerHello too short for the extensions length it declared was read past its end; it is refused now (#1286)
! Fix: httpsrv: a request which a limit of the service exceeded was answered anyway, the 503 every other service answers with taken for success; it is answered with 503 now, after the body of the request is drained
! Fix: httpsrv: a path ending in a backslashed dot-dot, or carrying one in a form the checks did not name, was taken as it stood; any dot-dot segment is refused wherever it is and whichever separator carries it, and a path ending in a bare dot of either kind
! Fix: pcre: a rule with no ACL was handed to the filters as the connection's data, which they read as a match data block and freed: a pointer into the configuration, dereferenced as another type and given back to malloc; a rule without an ACL now skips the check and goes on with a block of its own
+12 -12
View File
@@ -1,13 +1,13 @@
3proxy-1.0.3 Вышел 7 Ноября 2026
3proxy-1.0.4 Вышел 21 Ноября 2026
! Исправление: аутентификация RADIUS: дайджест ответа копировал общий секрет сразу за принятыми байтами, так что ответ размером 4100 байт с секретом в 17 и более символов записывал до 47 байт секрета за буфер ответа на стеке, ещё до проверки подлинности ответа; дайджест теперь вычисляется по ответу и секрету на месте, ничего не записывая за буфер, а ответ принимается только с адреса и порта сервера, которому был адресован запрос, с совпадающими с запросом идентификатором и длиной: раньше отправитель ответа не проверялся вовсе
! Исправление: ответ PTR от сервера имён мог записать данные за буфер ответа на стеке: обход имён шёл до конца всего сообщения вместо конца данных записи и мог принять байт-указатель сжатия за длину метки (ответ размером 3841 байт и более выходил за сам буфер); теперь обход останавливается в конце данных записи, а сжатое, пустое или обрезанное имя не принимается
! Исправление: каждое соединение, проверяемое правилом pcre: (или regex:), сопоставлялось с единственным блоком данных сопоставления правила, в который пишет pcre2_match(): два соединения, сопоставляемые одновременно, конкурировали за него и портили память, приводя процесс к падению под нагрузкой; теперь каждое соединение получает собственный блок данных сопоставления
! Исправление: TLS: чтение, возможное только после записи, или запись только после чтения (например, когда TLS 1.3 отвечает на обновление ключей, а сокет больше не принимает данные) завершало соединение с ошибкой; каждый TLS-сокет теперь помнит, чего ждут его незавершённые чтение и запись, и poll() TLS-уровня ждёт именно этого
! Исправление: Windows: чтение или запись TLS, требующая повторного обращения к сокету, не распознавалась, и соединение завершалось с посторонней ошибкой: в месте чтения ошибки сокета устанавливалась ошибка libc (errno)
! Исправление: клиент обратного соединения (connect back, -R) оставался в accept() в ожидании соединения, которое забрал другой клиент той же службы, до следующего соединения, переживая свой тайм-аут и перезагрузку конфигурации; сокет обратного соединения теперь неблокирующий, и accept() без соединения не считается попыткой клиента
! Исправление: ftppr: ответ сервера, входящего по одному USER (230, как часто бывает у анонимного FTP) или отказывающего во входе, прочитывался, но не передавался клиенту, который оставался ждать ответа на свой PASS до тайм-аута (#1284)
! Исправление: плагины: StringsPlugin, обрезая строку таблицы строк на её конце, записывал NUL за строкой, в остатки в буфере от прочитанных раньше более длинных строк или за его конец; FilePlugin передавал в socksend() состояние TLS соединения вместо параметров клиента, и отправка таблицы строк по TLS-соединению читала состояние TLS как clientparam
+ -B (для TCP-служб) разбивает проходящий через tlspr ClientHello TLS посередине имени сервера (SNI), чтобы системы DPI, не собирающие его заново, не видели имя хоста; TCP_NODELAY, устанавливаемый по умолчанию, выключать нельзя, иначе ядро может снова склеить сегменты; -s сохраняет тот же эффект там, где -s не означает splice (#1283)
+ 3proxy --help (и сообщение об использовании при неверном запуске) перечисляет, с чем собран бинарник: TLS и его серверная библиотека, RADIUS, PCRE, IPv6, сокеты Unix, встроенный HTTP-сервер, прозрачное проксирование, ODBC и необязательные прокси-службы
+ Исходящее соединение, привязываемое к внешнему адресу, на Linux 4.2 и новее привязывается с IP_BIND_ADDRESS_NO_PORT: порт выбирает connect() для пары с адресом назначения, поэтому порты, занятые соединениями к другим адресам или закрывающиеся в TIME_WAIT, больше не исчерпывают эфемерный диапазон; bind() больше не завершался с результатом 12 при большом числе соединений и не тратил миллисекунды на поиск порта
! Исправление: socks: запрос SOCKS4a отвергался как соединение с нулевым адресом, хотя в SOCKS4a нулевой адрес означает, что назначение — имя, следующее за ним
! Исправление: auth: UDP ASSOCIATE проходит предварительную авторизацию, не зная назначения, от которого зависят её правила, поэтому её вердикт относится только к этой ассоциации и не сохраняется для последующих запросов
! Исправление: socks: UDP-ассоциация передавалась напрямую при сбое родителя, хотя правила требовали родителя; теперь она отвергается
! Исправление: socks: имя хоста с управляющими байтами или пробелами принималось как есть; теперь оно отвергается там, где читается
! Исправление: smtpp: имя входа из одного порта, без хоста, задавало порт, но не называло назначения для соединения; такое имя входа теперь отвергается
! Исправление: proxy: учётные данные раннего запроса в сохранённом соединении решали и для последующих запросов; теперь каждый запрос авторизуется своими учётными данными
! Исправление: встроенный http-сервер (httpsrv): учётные данные раннего запроса в сохранённом соединении решали и для последующих запросов; теперь каждый запрос авторизуется своими учётными данными
! Исправление: tlspr: ServerHello TLS, слишком короткий для объявленной длины расширений, читался за его концом; теперь он отвергается (#1286)
! Исправление: httpsrv: запрос, для которого превышен лимит службы, всё равно выполнялся: 503, которой отвечают остальные службы, принималась за успех; теперь отвечается 503, после того как тело запроса прочитано
! Исправление: httpsrv: путь, оканчивающийся экранированной точкой-точкой или несущий её в форме, которую проверки не называли, принимался как есть; теперь любой сегмент точка-точка отвергается, где бы он ни был и каким бы разделителем ни был записан, как и путь, оканчивающийся одиночной точкой любого вида
! Исправление: pcre: правило без ACL передавалось фильтрам как данные соединения, и они читали его как блок данных сопоставления и освобождали: указатель в конфигурацию, разыменованный как другой тип и возвращённый malloc; теперь правило без ACL пропускает проверку и идёт со своим блоком
+1 -1
View File
@@ -1 +1 @@
1.0.3
1.0.4
+6
View File
@@ -1,3 +1,9 @@
3proxy (1.0.4-1) buster; urgency=medium
*3proxy 1.0.4 initial build
-- z3APA3A <3apa3a@3proxy.org> Sat, 21 Nov 2026 09:08:54 +0000
3proxy (1.0.3-1) buster; urgency=medium
*3proxy 1.0.3 initial build
+11
View File
@@ -0,0 +1,11 @@
! Fix: socks: a SOCKS4a request was refused as a connect to the null address, although in SOCKS4a the null address means that the destination is the name which follows it
! Fix: auth: a UDP ASSOCIATE is pre-authorized without looking at the destination its rules depend on, so its verdict holds for that association alone and is not kept for later requests
! Fix: socks: a UDP association was relayed direct when its parent failed, although the rules demanded the parent; it is refused now
! Fix: socks: a host name with control bytes or spaces in it was taken as it stood; it is refused where it is read now
! Fix: smtpp: a login name of a port alone, without a host, set the port but named no destination to connect to; such a login is refused now
! Fix: proxy: the credentials of an earlier request on a kept-alive connection decided for the requests after it; every request is authorized by its own credentials now
! Fix: the built-in http server (httpsrv): the credentials of an earlier request on a kept-alive connection decided for the requests after it; every request is authorized by its own credentials now
! Fix: tlspr: a TLS ServerHello too short for the extensions length it declared was read past its end; it is refused now (#1286)
! Fix: httpsrv: a request which a limit of the service exceeded was answered anyway, the 503 every other service answers with taken for success; it is answered with 503 now, after the body of the request is drained
! Fix: httpsrv: a path ending in a backslashed dot-dot, or carrying one in a form the checks did not name, was taken as it stood; any dot-dot segment is refused wherever it is and whichever separator carries it, and a path ending in a bare dot of either kind
! Fix: pcre: a rule with no ACL was handed to the filters as the connection's data, which they read as a match data block and freed: a pointer into the configuration, dereferenced as another type and given back to malloc; a rule without an ACL now skips the check and goes on with a block of its own
+13 -6
View File
@@ -510,9 +510,13 @@ conditions.</p>
<i>&lt;radius_server_2</i>[:<i>port</i>][/<i>local_address_2</i>]
<br>
Configures RADIUS servers to be used for logging and
authentication (log and auth types must be set to radius).
port and local address to use with given server may be
specified. <br>
authentication (log and auth types must be set to radius). A
server is a name or an address, resolved when the
configuration is read. port and local address to use with
given server may be specified: the port named is the one
authentication is asked on, and the accounting requests of
the same server go to the port after it (1812 and 1813 by
default). <br>
Attributes within request: User-Name, Password: (username
and password if presented by client), Service Type:
Authenticate-Only, NAS-Port-Type: NAS-Port-Virtual,
@@ -534,9 +538,12 @@ experimental.</p>
<p style="margin-left:9%; margin-top: 1em"><b>nserver</b>
<i>&lt;ipaddr&gt;</i>[:<i>port</i>][/<i>tcp</i>] <br>
Nameserver to use for name resolutions. If none specified
system routines for name resolution is used. Optional port
number may be specified. If optional /tcp is added to IP
address, name resolution is performed over TCP. An IPv6
system routines for name resolution is used. A server that
answers with an error (FORMERR, SERVFAIL, REFUSED and the
like) is passed over for the next one, while a name answered
with no data, or as not there, ends the search. Optional
port number may be specified. If optional /tcp is added to
IP address, name resolution is performed over TCP. An IPv6
address has to be enclosed in square brackets: <b><br>
nserver 1.1.1.1 <br>
nserver [2001:4860:4860::8844] <br>
+7 -2
View File
@@ -506,7 +506,10 @@ network conditions.
\fI<NAS_SECRET>\fR \fI<radius_server_1\fR[:\fIport\fR][/\fIlocal_address_1\fR]\fR \fI<radius_server_2\fR[:\fIport\fR][/\fIlocal_address_2\fR]\fR
.br
Configures RADIUS servers to be used for logging and authentication (log and auth types
must be set to radius). port and local address to use with given server may be specified.
must be set to radius). A server is a name or an address, resolved when the
configuration is read. port and local address to use with given server may be specified:
the port named is the one authentication is asked on, and the accounting requests of
the same server go to the port after it (1812 and 1813 by default).
.br
Attributes within request: User-Name, Password: (username and password if presented by client),
Service Type: Authenticate-Only,
@@ -530,7 +533,9 @@ Use \fBauthcache\fR to speedup authentication. RADIUS feature is currently exper
.br
Nameserver to use for name resolutions. If none specified
system routines for name resolution is
used. Optional port number may be specified.
used. A server that answers with an error (FORMERR, SERVFAIL, REFUSED
and the like) is passed over for the next one, while a name answered
with no data, or as not there, ends the search. Optional port number may be specified.
If optional /tcp is added to IP address, name resolution is
performed over TCP.
An IPv6 address has to be enclosed in square brackets:
+1 -1
View File
@@ -1,5 +1,5 @@
Name: 3proxy
Version: 1.0.3
Version: 1.0.4
Release: 1%{?dist}
Summary: 3proxy tiny proxy server
License: GPL/LGPL/Apache/BSD
+4 -1
View File
@@ -125,7 +125,10 @@ int doauth(struct clientparam * param){
if(authfuncs->authorize &&
(res = (*authfuncs->authorize)(param)))
return res;
if(param->srv->authcachetype && authfuncs->authenticate && authfuncs->authenticate != cacheauth && param->username && (!(param->srv->authcachetype&4) || (!param->pwtype && param->password))){
/* A UDP ASSOCIATE is pre-authorized without looking at the
destination its rules depend on, so its verdict holds for
that association alone and is not kept for later requests. */
if(param->srv->authcachetype && param->preauth != 1 && authfuncs->authenticate && authfuncs->authenticate != cacheauth && param->username && (!(param->srv->authcachetype&4) || (!param->pwtype && param->password))){
struct authcache ac={.username=""};
if(param->username) {
+18
View File
@@ -542,11 +542,26 @@ int parsehost(int family, unsigned char *host, struct sockaddr *sa){
return ret;
}
/* A host name is written into the request lines of parent protocols and
matched against rules, so a control byte or a space in it could end a
line early or pose as another destination. A name carrying one is
refused where it is read, and every name a client sends is read on
its way to the field. */
int badhostname(const char *hostname){
const unsigned char *c;
if(!hostname) return 1;
for(c = (const unsigned char *)hostname; *c; c++)
if(*c <= ' ' || *c == 0x7f) return 1;
return 0;
}
int parsehostname(char *hostname, struct clientparam *param, uint16_t port){
char *sp=NULL,*se=NULL;
int ret = 0;
if(!hostname || !*hostname)return 2;
if(badhostname(hostname)) return 1;
if(*hostname == '[') se=strchr(hostname, ']');
if ((sp = strchr(se?se:hostname, ':'))) {
if(strchr(sp+1, ':'))sp = NULL;
@@ -560,6 +575,9 @@ int parsehostname(char *hostname, struct clientparam *param, uint16_t port){
port = atoi(sp+1);
*sp = ':';
}
/* A port alone overrides the port of a host already set; without
one it names no destination to connect to. */
if(!param->hostname || !*param->hostname) return 1;
*SAPORT(&param->req) = htons(port);
return 0;
}
+2 -2
View File
@@ -1776,8 +1776,8 @@ static int h_radius(int argc, unsigned char **argv){
*s = 0;
s++;
}
if( !getip46(46, argv[nradservers + 2], (struct sockaddr *)&radiuslist[nradservers].authaddr)) return 1;
if( s && !getip46(46, (unsigned char *)s, (struct sockaddr *)&radiuslist[nradservers].localaddr)) return 2;
if(parsehost(46, argv[nradservers + 2], (struct sockaddr *)&radiuslist[nradservers].authaddr)) return 1;
if(s && parsehost(46, (unsigned char *)s, (struct sockaddr *)&radiuslist[nradservers].localaddr)) return 2;
if(!*SAPORT(&radiuslist[nradservers].authaddr))*SAPORT(&radiuslist[nradservers].authaddr) = htons(1812);
port = ntohs(*SAPORT(&radiuslist[nradservers].authaddr));
radiuslist[nradservers].logaddr = radiuslist[nradservers].authaddr;
+2 -2
View File
@@ -224,12 +224,12 @@ void * dnsprchild(struct clientparam* param) {
}
buf[0] = cid[0];
buf[1] = cid[1];
if(buf[6] || buf[7]){
/* the answer goes to the client as it is, its code with no records
among them: the name not found is the server's word, not ours */
if(socksendto(param, param->clisock, (struct sockaddr *)&param->sincr, buf, len, conf.timeouts[SINGLEBYTE_L]*1000) != len){
RETURN(822);
}
RETURN(0);
}
}
if(!ip) {
+35 -6
View File
@@ -430,11 +430,12 @@ static int targetunsafe(const char *path)
#endif
}
if(!strncmp(path, "./", 2) || !strncmp(path, "../", 3)) return 1;
if(strstr(path, "/./") || strstr(path, "/../")) return 1;
if(strstr(path, "\\.\\") || strstr(path, "\\..\\")) return 1;
/* a dot-dot segment, with either separator, wherever it is in the
path: a walk out of the tree, or a file named to look like one */
if(strstr(path, "/..") || strstr(path, "\\..")) return 1;
if(strstr(path, "/./") || strstr(path, "\\.\\")) return 1;
p = path + strlen(path);
if(p - path >= 2 && !strcmp(p - 2, "/.")) return 1;
if(p - path >= 3 && !strcmp(p - 3, "/..")) return 1;
if(p - path >= 2 && (!strcmp(p - 2, "/.") || !strcmp(p - 2, "\\."))) return 1;
return 0;
}
@@ -1495,16 +1496,27 @@ static int httpsrv_request(struct clientparam *param, struct httpreq *r)
return 1;
}
}
if(i && i != 10){
if(i){
/* The body goes before the answer, as for any answer this server
gives: left in the stream it would be read as the next request. */
if(!r->drained){
if(r->contentlen) httpsrv_drain(param, r->contentlen);
r->drained = 1;
}
/* 10: a limit of the service was exceeded, which the other
services answer with 503. */
if(i == 10){
static const char body[] = "exceeded your limits\n";
r->hdrs = NULL;
r->maxage = -1;
r->keepalive = 0;
if(httpsrv_head(r, 503, "text/plain", (int64_t)sizeof(body) - 1, NULL)) return 1;
httpsrv_send(r, body, (int)sizeof(body) - 1);
}
/* 4 no credentials, 5 unknown user, 6 wrong password: all of them
should let the client offer credentials again. */
if(i >= 4 && i <= 6) op_authrequired(r);
else if(i >= 4 && i <= 6) op_authrequired(r);
else op_forbidden(r);
RETURN(i);
}
@@ -1606,6 +1618,23 @@ void * httpsrvchild(struct clientparam *param)
r.lasthost = lasthost;
param->res = 0;
/* What the request brought belongs to it alone. A connection
can carry a client's request after another's, as a reverse
proxy reuses its upstreams, so the credentials and the host
of an earlier request decide nothing for this one. */
if(param->username){
free(param->username);
param->username = NULL;
}
if(param->password){
free(param->password);
param->password = NULL;
}
if(param->hostname){
free(param->hostname);
param->hostname = NULL;
}
answered = httpsrv_request(param, &r);
handoff = r.handoff;
if(r.raw) free(r.raw);
+3 -2
View File
@@ -264,13 +264,14 @@ static FILTER_ACTION pcre_filter_client(void *fo, struct clientparam * param, vo
struct pcre_filter_data *rule = (struct pcre_filter_data *)fo;
struct pcre_client_data *pcd;
*fc = fo;
*fc = NULL;
if(!fo) return PASS;
if(!rule->acl) return CONTINUE;
if(rule->acl){
memset (&tmpace, 0, sizeof(struct ace));
tmpace.src = rule->acl->src;
res = pl->ACLMatches(&tmpace, param);
if(!res) return PASS;
}
/* the connection goes on with a match data of its own */
if(!(pcd = pl->mallocfunc(sizeof(struct pcre_client_data)))){
*fc = NULL;
+21
View File
@@ -340,6 +340,27 @@ for(;;){
clhdrofs_req = -1;
param->nolongdatfilter = 0;
/* What the request brought belongs to it alone. A connection can carry
a request after another's, so the credentials of an earlier request
decide nothing for this one. */
if(param->username){
free(param->username);
param->username = NULL;
}
if(param->password){
free(param->password);
param->password = NULL;
}
param->pwtype = 0;
if(param->extusername){
free(param->extusername);
param->extusername = NULL;
}
if(param->extpassword){
free(param->extpassword);
param->extpassword = NULL;
}
/* A connection waiting a while for its next request, or a tunnel, holds
no buffer: it is taken again once a request starts coming. */
if(buf && param->cliinbuf == param->clioffset){
+1
View File
@@ -370,6 +370,7 @@ void hashdelete(struct hashtable *ht, void* name);
int hashresolv(struct hashtable *ht, void* name, void* value, uint32_t *ttl);
int parsehost(int family, unsigned char *host, struct sockaddr *sa);
int badhostname(const char *hostname);
int parsehostname(char *hostname, struct clientparam *param, uint16_t port);
int parseusername(char *username, struct clientparam *param, int extpasswd);
int parseconnusername(char *username, struct clientparam *param, int extpasswd, uint16_t port);
+6
View File
@@ -156,7 +156,13 @@ uint32_t udpresolve(int af, unsigned char * name, unsigned char * value, uint32_
continue; /* question does not match the query */
}
if((na = buf[7] + (((unsigned short)buf[6])<<8)) < 1) {
switch(buf[3] & 0x0F){
case 0: /* the name has no address */
case 3: /* the name is not there */
return 0;
default: /* the server failed: ask the next one */
continue;
}
}
for(k = 13; k<len && buf[k]; k++) {
}
+4
View File
@@ -197,6 +197,10 @@ void * smtppchild(struct clientparam* param) {
}
}
/* A login has to end with a host to connect to: what follows reads the
host name, and without one there is nowhere to go. */
if(!param->hostname || !param->extusername){RETURN(669);}
#ifndef WITHMAIN
{
int action, reqbufsize, reqsize;
+6 -1
View File
@@ -119,7 +119,10 @@ void * sockschild(struct clientparam* param) {
}
res = socks5_setaddr(param->srv->family, c, buf, &param->req);
if(res == 1) {RETURN(997);}
if(res == 2 && command == 1) {RETURN(431);}
/* The null address is no destination to connect to, except in
SOCKS4a, where it says that the destination is the name which
follows it. */
if(res == 2 && ver == 5 && command == 1) {RETURN(431);}
param->sinsr = param->req;
myinet_ntop(*SAFAMILY(&param->sinsr), SAADDR(&param->sinsr), (char *)buf, 64);
break;
@@ -137,6 +140,7 @@ void * sockschild(struct clientparam* param) {
default:
RETURN(997);
}
if(badhostname((char *)buf)) {RETURN(21);}
if(param->hostname)free(param->hostname);
param->hostname = (unsigned char *)strdup((char *)buf);
if(!param->hostname){RETURN(21);}
@@ -159,6 +163,7 @@ void * sockschild(struct clientparam* param) {
param->service = S_SOCKS45;
if(sockgetlinebuf(param, CLIENT, buf, BUFSIZE - 1, 0, conf.timeouts[STRING_S]) < 0) {RETURN(441);}
buf[127] = 0;
if(badhostname((char *)buf)) {RETURN(21);}
if(param->hostname)free(param->hostname);
param->hostname = (unsigned char *)strdup((char *)buf);
if(!param->hostname){RETURN(21);}
+14 -10
View File
@@ -224,6 +224,7 @@ int parsehello(int type, unsigned char *hello, unsigned len, char *sni, int * sn
else if(type == 2){
offset += 3;
}
if((offset + 2) > len) return -6;
elen = size16(hello+offset);
offset += 2;
if(elen+offset != len) return -9;
@@ -334,6 +335,7 @@ void * tlsprchild(struct clientparam* param) {
int lv=-1;
char proto[PROTOLEN]="-";
int snipos = 0;
int snlen = 0;
PROXYSERVICE stlsproto = param->clientstarttls? param->clientstarttls :
(param->starttls? param->starttls : param->srv->srvstarttls);
@@ -357,16 +359,7 @@ void * tlsprchild(struct clientparam* param) {
}
else if (parsehostname(sni, param, param->srv->targetport? ntohs(param->srv->targetport):starttlsport(stlsproto))) RETURN (100);
if (!param->hostname)param->hostname = (unsigned char *)strdup(sni);
if(param->srv->s_option && snipos && res > 1){
int len;
len = socksend(param, param->remsock, param->clibuf+param->clioffset,snipos + (res/2), conf.timeouts[STRING_S]);
if(len != snipos + (res/2)){
RETURN(310);
}
param->clioffset += snipos + (res/2);
}
snlen = res;
}
else if (res < 0 && param->srv->requirecert) RETURN(310-res);
}
@@ -386,6 +379,17 @@ void * tlsprchild(struct clientparam* param) {
return (void *)param->redirectfunc;
}
if(param->srv->s_option && snipos && snlen > 1){
int len;
len = socksend(param, param->remsock, param->clibuf+param->clioffset,snipos + (snlen/2), conf.timeouts[STRING_S]);
if(len != snipos + (snlen/2)){
RETURN(310);
}
param->clioffset += snipos + (snlen/2);
}
if(stlsproto){
res = srvstarttls(param, stlsproto);
if(res){
+8 -4
View File
@@ -162,8 +162,10 @@ static void udpreset(struct clientparam *param)
/*
* Authorize param->req and (re)build the server side of the association:
* a parent proxy chain and/or an external address may be selected by the ACL.
* Returns the authorization result. param->remsock is INVALID_SOCKET if the
* socket can not be created, in this case the association can not continue.
* Returns the authorization result. param->remsock is INVALID_SOCKET when
* the authorization refused the association or the socket can not be
* created; the association can not continue then, so that a parent the
* rules demand is never quietly replaced by a direct relay.
*/
static int udpreconnect(struct clientparam *param)
{
@@ -189,10 +191,11 @@ static int udpreconnect(struct clientparam *param)
param->remsock = INVALID_SOCKET;
}
udpreset(param);
}
if (udpbind(param)) return res? res : 11;
return res;
}
if (udpbind(param)) return 11;
return 0;
}
int udpsockmap(struct clientparam *param, int timeo)
{
@@ -281,6 +284,7 @@ int udpsockmap(struct clientparam *param, int timeo)
if (len < 7 + sz) return 485;
memcpy(dstnamebuf, base + 5, sz);
dstnamebuf[sz] = 0;
if (badhostname(dstnamebuf)) continue;
dstname = dstnamebuf;
i = 5 + sz;
if (!getip46(param->srv->family, (unsigned char *)dstnamebuf,
+4 -4
View File
@@ -1,14 +1,14 @@
#ifndef VERSION
#define VERSION "3proxy-1.0.3"
#define VERSION "3proxy-1.0.4"
#endif
#ifndef BUILDDATE
#define BUILDDATE "261107085016"
#define BUILDDATE "261121090854"
#endif
#define MAJOR3PROXY 1
#define SUBMAJOR3PROXY 0
#define MINOR3PROXY 3
#define MINOR3PROXY 4
#define SUBMINOR3PROXY 0
#define RELEASE3PROXY "3proxy-1.0.3(" BUILDDATE ")\0"
#define RELEASE3PROXY "3proxy-1.0.4(" BUILDDATE ")\0"
#ifndef YEAR3PROXY
#define YEAR3PROXY "2026"
#endif
+18
View File
@@ -1,5 +1,7 @@
"""Authentication and access rules in front of the HTTP server."""
import base64
def run(t):
if not t.skip_unless("httpsrv"):
@@ -49,3 +51,19 @@ def run(t):
t.contains(t.http(url + "/echo", auth=("alice", "secret")), "path=/echo",
"an authenticated request is dispatched")
# --- credentials do not outlive the request that carried them ------
# A kept connection answers a second request without credentials as
# unauthenticated: a reverse proxy reuses its upstreams between
# clients, so one client's login must not open another's way in.
creds = base64.b64encode(b"alice:secret").decode()
text, closed = t.raw_session(srv,
f"GET /echo HTTP/1.1\r\nHost: t\r\n"
f"Authorization: Basic {creds}\r\n\r\n"
f"GET /echo HTTP/1.1\r\nHost: t\r\nConnection: close\r\n\r\n")
parts = text.split("HTTP/1.")
t.eq(3, len(parts), "the kept connection answers both requests")
t.eq(True, parts[1].startswith("1 200"),
"the request with credentials is allowed")
t.eq(True, parts[2].startswith("0 401"),
"the request after it, without credentials, is refused")
+88
View File
@@ -0,0 +1,88 @@
"""Name resolution: a server answering with an error is passed over, one
that says the name is not there ends the search.
A proxy resolves the destination by asking the configured name servers in
order. The first one here answers FORMERR to everything; the second answers
from a list. A request through the proxy reaches its destination, which
proves the second server was asked, and a name the second server says is
not there is not resolved by anyone else.
"""
import socket
import struct
import threading
class DnsServer:
"""Answers every query with a fixed rcode, and A records for names it
knows: the question is echoed, so the answer parses everywhere."""
def __init__(self, rcode, records):
self.rcode = rcode
self.records = records
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.bind(("127.0.0.1", 0))
self.port = self.sock.getsockname()[1]
self.thread = threading.Thread(target=self.serve, daemon=True)
def serve(self):
while True:
try:
data, addr = self.sock.recvfrom(65536)
except OSError:
return
if len(data) >= 12:
self.sock.sendto(self.reply(data), addr)
def reply(self, query):
if self.rcode:
return (query[:2] + struct.pack("!HHHHH", 0x8180 | self.rcode, 1, 0, 0, 0)
+ query[12:])
name = b""
pos = 12
while query[pos]:
name += query[pos + 1:pos + 1 + query[pos]] + b"."
pos += query[pos] + 1
name = name[:-1]
answer = self.records.get(name)
if not answer:
return (query[:2] + struct.pack("!HHHHH", 0x8183, 1, 0, 0, 0)
+ query[12:])
return (query[:2] + struct.pack("!HHHHH", 0x8180, 1, 1, 0, 0) + query[12:]
+ b"\xc0\x0c" + struct.pack("!HHIH", 1, 1, 60, 4)
+ socket.inet_aton(answer))
def start(self):
self.thread.start()
return self.port
def run(t):
broken = DnsServer(1, {}).start()
good = DnsServer(0, {b"here.test": "127.0.0.1"}).start()
# the destination the resolved name points at: a one-page origin
origin = t.free_port()
page = t.raw_server(origin, b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
b"\r\nok", close_after=True)
proxy = t.free_port()
t.start("nsfailover", f"""
log
flush
nserver 127.0.0.1:{broken}
nserver 127.0.0.1:{good}
auth iponly
allow *
proxy -p{proxy}
""", ports=[origin, proxy])
url = f"http://here.test:{origin}/"
t.eq(200, t.http(url, proxy=f"127.0.0.1:{proxy}").status,
"a name one server breaks is resolved by the next one")
r = t.http(f"http://gone.test:{origin}/", proxy=f"127.0.0.1:{proxy}")
t.ne(200, r.status if r else 0,
"a name the last server says is not there does not resolve")
page()
+97
View File
@@ -9,9 +9,22 @@ The number of attempts is bounded by parentretries, two by default, so each
case here needs at most one parent to fail before a working one is reached.
"""
import socket
import struct
import time
def recvall(sock, count):
"""Bytes from a socket, fewer only when the peer stops sending."""
data = b""
while len(data) < count:
chunk = sock.recv(count - len(data))
if not chunk:
break
data += chunk
return data
def served(server, needle, since=0):
"""How many log lines carrying needle a proxy wrote past offset since."""
return sum(1 for line in server.output()[since:].splitlines() if needle in line)
@@ -152,6 +165,90 @@ def run(t):
t.eq(1, wait_served(goodp, needle, 1, gmark),
"through the parent it names")
# --- UDP: a parent which is down is not replaced by a direct relay -------
# The association itself is allowed without its destination, but the
# datagram carrying one has to build the chain its rule demands. With
# the only parent gone the association has to fail: relaying the next
# datagram from the proxy's own address would be a way around the rule.
sudp = t.free_port()
t.start("failover_udp", f"""
log
auth iponly
allow *
parent 1000 socks5 127.0.0.1 {dead}
socks -p{sudp}
""", ports=[sudp])
echo1 = t.udp_echo()
echo2 = t.udp_echo()
ctrl = socket.create_connection(("127.0.0.1", sudp), t.timeout)
ctrl.settimeout(t.timeout)
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp.settimeout(1.0)
try:
ctrl.sendall(b"\x05\x01\x00")
greeted = recvall(ctrl, 2) == b"\x05\x00"
ctrl.sendall(b"\x05\x03\x00\x01\x00\x00\x00\x00\x00\x00")
reply = recvall(ctrl, 4)
bound = None
if greeted and len(reply) >= 4 and reply[1] == 0 and reply[3] == 1:
addr = recvall(ctrl, 6)
if len(addr) == 6:
bound = struct.unpack("!H", addr[4:6])[0]
def datagram(port, payload):
header = (b"\x00\x00\x00\x01" + socket.inet_aton("127.0.0.1") +
struct.pack("!H", port))
udp.sendto(header + payload, ("127.0.0.1", bound))
def silence(port, payload):
"""Whether nothing came back for the datagram sent."""
datagram(port, payload)
try:
udp.recvfrom(65536)
return False
except OSError:
return True
if bound is None:
t.fail("the association is granted", expected="a relay port",
actual=None)
else:
t.eq(True, silence(echo1, b"first"),
"the datagram to the dead parent is not delivered")
try:
closed = ctrl.recv(1) == b""
except OSError:
closed = False
t.eq(True, closed,
"the association does not survive its failed parent")
t.eq(True, silence(echo2, b"second"),
"no datagram after it is relayed direct")
finally:
ctrl.close()
udp.close()
# a parent which carries UDP is used for UDP: the failover above is the
# parent's failure, not the relay's refusal
suparent = t.free_port()
sup = t.free_port()
t.start("failover_udp_parent", f"""
log
auth iponly
allow *
socks -p{suparent}
""", ports=[suparent])
t.start("failover_udp_up", f"""
log
auth iponly
allow *
parent 1000 socks5 127.0.0.1 {suparent}
socks -p{sup}
""", ports=[sup])
reply, _ = t.socks_udp(f"127.0.0.1:{sup}", "127.0.0.1", echo1, b"udp")
t.eq(b"echo:udp", reply, "a datagram is carried by the working parent")
# --- what the parser still rejects --------------------------------------
out = t.run_config("failover_badweight", f"""
auth iponly
+17
View File
@@ -4,6 +4,8 @@ Access rules accumulate until "flush", so each service section here starts
from a clean list.
"""
import base64
def run(t):
if not t.skip_unless("httpsrv"):
@@ -108,3 +110,18 @@ def run(t):
t.eq(407, t.http(origin + "/echo", proxy=needs_auth,
proxy_auth=("alice", "wrong")).status,
"wrong proxy credentials are refused")
# credentials do not outlive the request which carried them: a second
# request on the same connection, without them, is asked again
creds = base64.b64encode(b"alice:secret").decode()
text, closed = t.raw_session(auth,
f"GET {origin}/echo HTTP/1.1\r\nHost: 127.0.0.1:{srv}\r\n"
f"Proxy-Authorization: Basic {creds}\r\n\r\n"
f"GET {origin}/echo HTTP/1.1\r\nHost: 127.0.0.1:{srv}\r\n"
f"Connection: close\r\n\r\n")
parts = text.split("HTTP/1.")
t.eq(3, len(parts), "the kept connection answers both requests")
t.eq(True, parts[1].startswith("1 200"),
"the request with credentials is allowed")
t.eq(True, parts[2].startswith("0 407"),
"the request after it, without credentials, is refused")
+42
View File
@@ -0,0 +1,42 @@
"""The radius command: a server may be a name, an address, and carry a
port, with an IPv6 address in brackets.
The port was in the man page but not in the code before: a server with a
port was simply refused. A name is resolved when the configuration is
read, with the name servers in force or the system's.
"""
def run(t):
def accepted(config):
out = t.run_config("radius_cmd", config + "\nnot_a_command\n")
return "'radius' failed" not in out, out
ok, out = accepted("log\nradius s3cret 127.0.0.1:18120")
if ok:
t.ok("a server address with a port is accepted")
else:
t.fail("a server address with a port is accepted",
"'radius' not refused", out)
ok, out = accepted("log\nradius s3cret localhost")
if ok:
t.ok("a server name is accepted, resolved when the file is read")
else:
t.fail("a server name is accepted, resolved when the file is read",
"'radius' not refused", out)
if t.has_ipv6():
ok, out = accepted("log\nradius s3cret [::1]:18120")
if ok:
t.ok("an IPv6 server address in brackets, with a port, is accepted")
else:
t.fail("an IPv6 server address in brackets, with a port, is accepted",
"'radius' not refused", out)
out = t.run_config("radius_bad",
"log\nradius s3cret 999.999.999.999\nnot_a_command\n")
t.contains(out, "'radius' failed",
"an address that is none is refused")
t.not_contains(out, "'not_a_command'",
"and the file stops at the refused line")
+91
View File
@@ -0,0 +1,91 @@
"""The SMTP proxy login: what it may be sent, and what may not be done."""
import base64
import socket
def recvline(sock):
"""One reply line, shorter only when the peer stops sending."""
data = b""
while not data.endswith(b"\n"):
chunk = sock.recv(1)
if not chunk:
break
data += chunk
return data
def drain_ehlo(sock):
"""Read the multi-line EHLO answer up to its last line."""
while True:
line = recvline(sock)
if not line or line.startswith(b"250 "):
return
def run(t):
if not t.skip_unless("smtpp"):
return
sp = t.free_port()
pp = t.free_port()
t.start("smtpp_login", f"""
log
auth iponly
allow *
proxy -p{pp}
flush
auth none
allow *
smtpp -p{sp}
""", ports=[pp, sp])
def auth_login(name):
"""The reply the login ends with for the given name."""
with socket.create_connection(("127.0.0.1", sp), t.timeout) as s:
s.settimeout(t.timeout)
recvline(s)
s.sendall(b"EHLO case\r\n")
drain_ehlo(s)
s.sendall(b"AUTH LOGIN\r\n")
recvline(s)
s.sendall(base64.b64encode(name) + b"\r\n")
reply = recvline(s)
# the name carries the destination, so a refusal can come with
# the username already, before any password is asked for
if not reply.startswith(b"334"):
return reply
s.sendall(base64.b64encode(b"pw") + b"\r\n")
return recvline(s)
def auth_plain(name):
"""The reply of a one-line AUTH PLAIN carrying the given name."""
with socket.create_connection(("127.0.0.1", sp), t.timeout) as s:
s.settimeout(t.timeout)
recvline(s)
s.sendall(b"EHLO case\r\n")
drain_ehlo(s)
s.sendall(b"AUTH PLAIN " +
base64.b64encode(b"\x00" + name + b"\x00pw") +
b"\r\n")
return recvline(s)
# A name of a port alone names no destination: the login is refused
# with a reply, and the daemon is left standing, its other listeners
# among them.
t.contains(auth_login(b"x@:25"), b"571",
"a login name of a port alone is refused")
t.contains(auth_plain(b"x@:25"), b"571",
"the same name over AUTH PLAIN is refused")
t.contains(auth_login(b"x@127.0.0.1:9"), b"571",
"a login name of a dead host is refused")
with socket.create_connection(("127.0.0.1", sp), t.timeout) as s:
s.settimeout(t.timeout)
t.eq(True, recvline(s).startswith(b"220"),
"the SMTP proxy answers again after the refused logins")
try:
with socket.create_connection(("127.0.0.1", pp), t.timeout):
t.ok("the other services of the process keep accepting")
except OSError:
t.fail("the other services of the process keep accepting")
+132
View File
@@ -1,5 +1,19 @@
"""The SOCKS proxy, reaching the built-in server."""
import socket
import struct
def recvall(sock, count):
"""Bytes from a socket, fewer only when the peer stops sending."""
data = b""
while len(data) < count:
chunk = sock.recv(count - len(data))
if not chunk:
break
data += chunk
return data
def run(t):
if not t.skip_unless("httpsrv"):
@@ -96,3 +110,121 @@ def run(t):
"wrong SOCKS5 credentials are refused")
t.ne(None, t.socks_connect(guarded, "127.0.0.1", srv),
"SOCKS5 without credentials is refused")
# --- names a client may not choose -------------------------------------
# A destination name travels into the request lines of parent protocols,
# so a control byte or a space in it could end the line early and name
# another destination. Such a name is refused where it is read, before
# anything is resolved or connected: reply 1, not the reply of a
# destination which does not answer.
sname = t.free_port()
standin = t.free_port()
t.start("socks_names", f"""
log
fakeresolve
auth iponly
allow *
socks -p{sname}
""", ports=[sname])
def socks5_name(name, port):
"""The reply code of a SOCKS5 CONNECT naming the given name."""
with socket.create_connection(("127.0.0.1", sname), t.timeout) as s:
s.settimeout(t.timeout)
s.sendall(b"\x05\x01\x00")
if recvall(s, 2) != b"\x05\x00":
return None
s.sendall(b"\x05\x01\x00\x03" + bytes([len(name)]) + name +
struct.pack("!H", port))
reply = recvall(s, 4)
return reply[1] if len(reply) > 1 else None
def socks4_name(name, port):
"""The reply code of a SOCKS4a CONNECT naming the given name."""
with socket.create_connection(("127.0.0.1", sname), t.timeout) as s:
s.settimeout(t.timeout)
s.sendall(struct.pack(">BBH", 4, 1, port) +
socket.inet_aton("0.0.0.0") + b"case\x00" + name +
b"\x00")
reply = recvall(s, 8)
return reply[1] if len(reply) > 1 else None
t.eq(1, socks5_name(b"127.0.0.1\r\nGET /other HTTP/1.1\r\n\r\nstand-in.example",
standin),
"a name with CR LF in it is refused")
t.eq(91, socks4_name(b"127.0.0.1\r\nGET /other HTTP/1.1\r\n\r\nstand-in.example",
standin),
"SOCKS4a refuses a name with CR LF in it")
t.eq(1, socks5_name(b"127.0.0.1 stand-in.example", standin),
"a name with a space in it is refused")
t.eq(1, socks5_name(b"stand-in\x7f.example", standin),
"a name with a control byte in it is refused")
# a well-formed name is let through, to the 127.0.0.2 fakeresolve maps
# every name to; where that address can be served, the tunnel has to be
# carried all the way to it
probe = socket.socket()
try:
probe.bind(("127.0.0.2", 0))
except OSError:
probe.close()
t.skip("the stand-in address 127.0.0.2 can not be bound here")
else:
probe.close()
stop = t.raw_server(standin, b"from the stand-in\r\n",
host="127.0.0.2")
t.eq(0, socks5_name(b"stand-in.example", standin),
"a well-formed name is connected by name")
t.eq(90, socks4_name(b"stand-in.example", standin),
"a well-formed name is connected by name over SOCKS4a")
stop()
# --- a pre-authorized association decides nothing for later ------------
# A UDP ASSOCIATE is allowed without looking at the destination its rules
# name, so that verdict may not be kept in the auth cache and returned
# for a CONNECT later.
scache = t.free_port()
allowed = t.free_port()
denied = t.free_port()
t.start("socks_cacheacl", f"""
log
authcache user,pass,dstport 60
auth cacheacl strong
users u:CL:p
allow u * * {allowed}
deny *
socks -p{scache}
""", ports=[scache])
# both destinations are alive: what decides between them is the rule
stop = t.raw_server(allowed, b"from the allowed stand-in\r\n")
refuse = t.raw_server(denied, b"from the refused stand-in\r\n")
def associate_declared():
"""The reply code of a UDP ASSOCIATE naming the refused destination."""
with socket.create_connection(("127.0.0.1", scache), t.timeout) as s:
s.settimeout(t.timeout)
s.sendall(b"\x05\x01\x02")
reply = recvall(s, 2)
if len(reply) < 2 or reply[1] != 0x02:
return None
s.sendall(b"\x01\x01u\x01p")
reply = recvall(s, 2)
if len(reply) < 2 or reply[1] != 0:
return None
s.sendall(b"\x05\x03\x00\x01" + socket.inet_aton("127.0.0.1") +
struct.pack("!H", denied))
reply = recvall(s, 4)
return reply[1] if len(reply) > 1 else None
guarded = f"127.0.0.1:{scache}"
t.eq(None, t.socks_connect(guarded, "127.0.0.1", allowed, auth=("u", "p")),
"a CONNECT the rules allow is connected")
t.ne(None, t.socks_connect(guarded, "127.0.0.1", denied, auth=("u", "p")),
"a CONNECT the rules refuse is refused")
t.eq(0, associate_declared(),
"the association itself is allowed without its destination")
t.ne(None, t.socks_connect(guarded, "127.0.0.1", denied, auth=("u", "p")),
"a CONNECT after the association is refused all the same")
stop()
refuse()