mirror of
https://github.com/3proxy/3proxy.git
synced 2026-11-26 23:59:41 +08:00
Compare commits
No files matched your search
@@ -1,25 +1,13 @@
|
|||||||
3proxy-1.0.2 Released October, 24 2026
|
3proxy-1.0.4 Released November, 21 2026
|
||||||
|
|
||||||
! Fix: dnspr relayed to the client whatever came first to the socket it asked the name server from, from any address and under any id, so a forged answer could be passed on; the query now goes out under a random id, and only an answer from the name server asked, with that id and the same question, is relayed
|
! 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: a client sending a part of a TLS record and then nothing kept a thread taking all of a CPU, and the read never timed out
|
! 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: without -Ne, the reply to SOCKS CONNECT and BIND gave the address of the client's connection to the proxy instead of the socket towards the destination: a BIND client was told the proxy's own port and the peer could never reach it (since 0.9.6)
|
! Fix: socks: a UDP association was relayed direct when its parent failed, although the rules demanded the parent; it is refused now
|
||||||
! Fix: a client which shut down its sending side (half-close) could get the answer cut short, megabytes short with large answers; likewise an upload after the server half-closed
|
! 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: with chroot every local time was UTC and every syslog message was lost: the time zone is loaded and syslog connected before chroot; the chroot entry of 3proxy.cfg(5) lists what PAM, LDAP and ODBC still need inside the chroot
|
! 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: the HTTP proxy closed the server connection of a kept-alive client and opened another one when only the request method changed (a POST after a GET to the same host)
|
! 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 last ssl_client_mode in the configuration applied to every service, and a reload changed it for the services still running
|
! 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: memory leaks: on every refused configuration reload, on every failed TLS handshake, the server CA paths of every TLS service, compiled pcre: / regex: host names of access rules and patterns of httpsrv rules
|
! Fix: tlspr: a TLS ServerHello too short for the extensions length it declared was read past its end; it is refused now (#1286)
|
||||||
! Fix: Unix sockets: on Linux a proxy listening on a Unix socket relayed only the first bytes of an answer (result 95); an abstract socket (unix:@NAME) was bound under a name padded with zeros, which clients did not reach; tcppm refused port 0 for a unix: target, as given in the manual's example; on a reload the socket file of a listening service was removed
|
! 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: SIGPIPE could kill 3proxy when a client was gone while services were starting, and standalone services (proxy, socks, ...) at any time; sends use MSG_NOSIGNAL where the system has it
|
! 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: TLS MitM failed for every connection with wolfSSL built with WOLFSSL_QT (wolfSSL 5.9.1 of Ubuntu 26.04): the source certificate's serial number could not be copied; a serial number made from the hash of the source certificate is used then
|
! 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
|
||||||
! Fix: Windows: closing a connection could leave its socket open (SO_LINGER on a non-blocking socket) or reset it while the peer still sent, so the end of an answer could be lost
|
|
||||||
! Fix: httpsrv: the body of a request answered without being read (for example when authentication is required) was read as the next request; a client still sending when a connection without keep-alive closed could get a reset instead of the answer
|
|
||||||
! Fix: httpsrv on Windows: UNC paths (\\server\share) did not work
|
|
||||||
! Fix: httpsrv and admin services and their clients were named ZOMBIE on the admin services page, in %N of logs and in RADIUS
|
|
||||||
! Fix: the Watcom (lite) build did not compile, 1.0.1 had no binaries for it
|
|
||||||
+ -s (splice) per direction: -s1 splices what the server sends (downloads), -s2 what the client sends (uploads), -s3 both; -s alone splices only where it pays (large bodies, long streams); pipes are kept with the connection for its next requests. splice() is built by default on Linux again and is used only by services given -s
|
|
||||||
+ Socket options (-oc, -os, -ol, -or, -oR) take NAME=VALUE; NAME=0 turns an option off, also one set by default; an unknown name or a value which is not a number is an error
|
|
||||||
+ The HTTP proxy frees its 64 KB request buffer while a CONNECT tunnel relays data and while a kept-alive connection waits for its next request: 2000 tunnels take 213 MB instead of 339 MB
|
|
||||||
+ TLS records are read ahead with OpenSSL 1.1.0 and later: decrypting takes 9-14% less CPU
|
|
||||||
+ Faster service stop and configuration reload, no fixed delays; a connection waiting for a free maxconn slot gets it at once
|
|
||||||
- TCP_NODELAY is set by default on proxy-to-client and proxy-to-server sockets; -ocTCP_NODELAY=0 / -osTCP_NODELAY=0 turns it off
|
|
||||||
- The HTTP proxy fetches ftp:// URLs only when the service is given the new -Xftp option (in a build with FTP=true)
|
|
||||||
+12
-24
@@ -1,25 +1,13 @@
|
|||||||
3proxy-1.0.2 Вышел 24 Октября 2026
|
3proxy-1.0.4 Вышел 21 Ноября 2026
|
||||||
|
|
||||||
! Исправление: dnspr передавал клиенту то, что первым пришло на сокет, с которого он обращался к серверу имён, с любого адреса и с любым id, так что поддельный ответ мог быть передан клиенту; теперь запрос отправляется со случайным id, и передаётся только ответ от того сервера имён, к которому обращались, с этим id и тем же вопросом
|
! Исправление: socks: запрос SOCKS4a отвергался как соединение с нулевым адресом, хотя в SOCKS4a нулевой адрес означает, что назначение — имя, следующее за ним
|
||||||
! Исправление: клиент, отправивший часть записи TLS и затем ничего, занимал поток на всё процессорное время, и чтение не завершалось по таймауту
|
! Исправление: auth: UDP ASSOCIATE проходит предварительную авторизацию, не зная назначения, от которого зависят её правила, поэтому её вердикт относится только к этой ассоциации и не сохраняется для последующих запросов
|
||||||
! Исправление: без -Ne ответ на SOCKS CONNECT и BIND содержал адрес соединения клиента с прокси вместо адреса сокета в сторону назначения: клиенту BIND сообщался собственный порт прокси, и удалённая сторона не могла к нему подключиться (с 0.9.6)
|
! Исправление: socks: UDP-ассоциация передавалась напрямую при сбое родителя, хотя правила требовали родителя; теперь она отвергается
|
||||||
! Исправление: клиент, закрывший свою сторону передачи (half-close), мог получить ответ не полностью, на больших ответах без нескольких мегабайт; так же обрезалась загрузка на сервер после того, как сервер закрыл свою сторону
|
! Исправление: socks: имя хоста с управляющими байтами или пробелами принималось как есть; теперь оно отвергается там, где читается
|
||||||
! Исправление: при chroot всё местное время становилось UTC и все сообщения syslog терялись: часовой пояс теперь загружается, а syslog подключается до chroot; в описании chroot в 3proxy.cfg(5) перечислено, что ещё нужно внутри chroot для PAM, LDAP и ODBC
|
! Исправление: smtpp: имя входа из одного порта, без хоста, задавало порт, но не называло назначения для соединения; такое имя входа теперь отвергается
|
||||||
! Исправление: HTTP прокси закрывал соединение с сервером для клиента с keep-alive и открывал новое, когда менялся только метод запроса (POST после GET к тому же хосту)
|
! Исправление: proxy: учётные данные раннего запроса в сохранённом соединении решали и для последующих запросов; теперь каждый запрос авторизуется своими учётными данными
|
||||||
! Исправление: последний ssl_client_mode в конфигурации действовал для всех служб, а перезагрузка конфигурации меняла его для уже работающих служб
|
! Исправление: встроенный http-сервер (httpsrv): учётные данные раннего запроса в сохранённом соединении решали и для последующих запросов; теперь каждый запрос авторизуется своими учётными данными
|
||||||
! Исправление: утечки памяти: при каждой отвергнутой перезагрузке конфигурации, при каждом неудачном согласовании TLS, пути CA сервера каждой службы с TLS, скомпилированные имена хостов pcre: / regex: в правилах доступа и шаблоны правил httpsrv
|
! Исправление: tlspr: ServerHello TLS, слишком короткий для объявленной длины расширений, читался за его концом; теперь он отвергается (#1286)
|
||||||
! Исправление: сокеты Unix: в Linux прокси, слушающий на сокете Unix, передавал только первые байты ответа (результат 95); абстрактный сокет (unix:@NAME) привязывался к имени, дополненному нулями, до которого клиенты не доходили; tcppm отвергал порт 0 для цели unix:, как в примере из документации; при перезагрузке конфигурации файл сокета слушающей службы удалялся
|
! Исправление: httpsrv: запрос, для которого превышен лимит службы, всё равно выполнялся: 503, которой отвечают остальные службы, принималась за успех; теперь отвечается 503, после того как тело запроса прочитано
|
||||||
! Исправление: SIGPIPE мог завершить 3proxy, если клиент отключался во время запуска служб, а отдельные службы (proxy, socks, ...) — в любой момент; отправка данных использует MSG_NOSIGNAL там, где система его поддерживает
|
! Исправление: httpsrv: путь, оканчивающийся экранированной точкой-точкой или несущий её в форме, которую проверки не называли, принимался как есть; теперь любой сегмент точка-точка отвергается, где бы он ни был и каким бы разделителем ни был записан, как и путь, оканчивающийся одиночной точкой любого вида
|
||||||
! Исправление: TLS MitM не работал ни для одного соединения с wolfSSL, собранным с WOLFSSL_QT (wolfSSL 5.9.1 в Ubuntu 26.04): не удавалось скопировать серийный номер исходного сертификата; в этом случае используется серийный номер, полученный из хеша исходного сертификата
|
! Исправление: pcre: правило без ACL передавалось фильтрам как данные соединения, и они читали его как блок данных сопоставления и освобождали: указатель в конфигурацию, разыменованный как другой тип и возвращённый malloc; теперь правило без ACL пропускает проверку и идёт со своим блоком
|
||||||
! Исправление: Windows: при закрытии соединения сокет мог остаться открытым (SO_LINGER на неблокирующем сокете) или соединение сбрасывалось, пока другая сторона ещё передавала данные, так что конец ответа мог потеряться
|
|
||||||
! Исправление: httpsrv: тело запроса, на который ответ дан без его чтения (например, когда требуется аутентификация), читалось как следующий запрос; клиент, ещё передающий данные при закрытии соединения без keep-alive, мог получить сброс соединения вместо ответа
|
|
||||||
! Исправление: httpsrv в Windows: не работали пути UNC (\\server\share)
|
|
||||||
! Исправление: службы httpsrv и admin и их клиенты назывались ZOMBIE на странице служб admin, в %N журнала и в RADIUS
|
|
||||||
! Исправление: сборка Watcom (lite) не компилировалась, в 1.0.1 для неё не было двоичных файлов
|
|
||||||
+ -s (splice) по направлениям: -s1 — то, что передаёт сервер (скачивание), -s2 — то, что передаёт клиент (загрузка), -s3 — оба; -s без числа использует splice только там, где это выгодно (большие тела, длинные потоки); каналы (pipe) сохраняются с соединением для следующих запросов. splice() снова собирается по умолчанию в Linux и используется только службами с -s
|
|
||||||
+ Опции сокетов (-oc, -os, -ol, -or, -oR) принимают ИМЯ=ЗНАЧЕНИЕ; ИМЯ=0 выключает опцию, в том числе установленную по умолчанию; неизвестное имя или значение, не являющееся числом, — ошибка
|
|
||||||
+ HTTP прокси освобождает буфер запроса размером 64 КБ, пока туннель CONNECT передаёт данные и пока соединение с keep-alive ждёт следующего запроса: 2000 туннелей занимают 213 МБ вместо 339 МБ
|
|
||||||
+ Записи TLS читаются с упреждением (read-ahead) с OpenSSL 1.1.0 и новее: расшифровка занимает на 9-14% меньше процессорного времени
|
|
||||||
+ Более быстрая остановка служб и перезагрузка конфигурации, без фиксированных задержек; соединение, ожидающее свободного места в maxconn, получает его сразу
|
|
||||||
- TCP_NODELAY устанавливается по умолчанию на сокетах прокси-клиент и прокси-сервер; -ocTCP_NODELAY=0 / -osTCP_NODELAY=0 выключает его
|
|
||||||
- HTTP прокси обрабатывает адреса ftp:// только если службе задана новая опция -Xftp (в сборке с FTP=true)
|
|
||||||
@@ -8,7 +8,8 @@
|
|||||||
|
|
||||||
- **Master** (current/latest) branch - 3proxy 1.0
|
- **Master** (current/latest) branch - 3proxy 1.0
|
||||||
- **0.9** (LTS) branch - 3proxy 0.9.9.x
|
- **0.9** (LTS) branch - 3proxy 0.9.9.x
|
||||||
- **Devel** branch - 3proxy 2.0-devel (don't use it)
|
- **Devel** branch - 3proxy 1.1 (development, don't use it in production)
|
||||||
|
- **Experimental** branch - 3proxy 2.0 (experimental, don't use it)
|
||||||
|
|
||||||
### Binaries (deb / rpm / Windows zip)
|
### Binaries (deb / rpm / Windows zip)
|
||||||
|
|
||||||
|
|||||||
Vendored
+12
@@ -1,3 +1,15 @@
|
|||||||
|
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
|
||||||
|
|
||||||
|
-- z3APA3A <3apa3a@3proxy.org> Sat, 07 Nov 2026 08:50:16 +0000
|
||||||
|
|
||||||
3proxy (1.0.2-1) buster; urgency=medium
|
3proxy (1.0.2-1) buster; urgency=medium
|
||||||
|
|
||||||
*3proxy 1.0.2 initial build
|
*3proxy 1.0.2 initial build
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
! 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
|
||||||
@@ -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
|
||||||
@@ -648,16 +648,16 @@ see <a href="#DNSPR">How to set up a DNS proxy (dnspr)</a>.
|
|||||||
<br>tlspr can be used as a parent with the "tls" type to implement SNI splitting for DPI bypass (similar to NoDPI/GoodByeDPI).
|
<br>tlspr can be used as a parent with the "tls" type to implement SNI splitting for DPI bypass (similar to NoDPI/GoodByeDPI).
|
||||||
The client sends the first part of the TLS ClientHello, tlspr splits it at the SNI extension and sends it in two TCP packets,
|
The client sends the first part of the TLS ClientHello, tlspr splits it at the SNI extension and sends it in two TCP packets,
|
||||||
which can bypass some DPI systems that look for blocked hostnames in TLS handshakes.
|
which can bypass some DPI systems that look for blocked hostnames in TLS handshakes.
|
||||||
<br>To enable SNI break, use <code>parent ... tls 0.0.0.0 0</code> and the <code>-s</code> option on the listening service with TCP_NODELAY:
|
<br>To enable SNI break, use <code>parent ... tls 0.0.0.0 0</code> and the <code>-B</code> option on the listening service:
|
||||||
</p><pre>
|
</p><pre>
|
||||||
auth iponly
|
auth iponly
|
||||||
allow *
|
allow *
|
||||||
parent 1000 tls 0.0.0.0 0
|
parent 1000 tls 0.0.0.0 0
|
||||||
allow *
|
allow *
|
||||||
proxy -s -i127.0.0.1 -ocTCP_NODELAY -osTCP_NODELAY -p1443
|
proxy -B -i127.0.0.1 -p1443
|
||||||
</pre>
|
</pre>
|
||||||
<p>
|
<p>
|
||||||
TCP_NODELAY is required to prevent the kernel from merging the split packets.
|
TCP_NODELAY, set by default, is required to prevent the kernel from merging the split packets: do not turn it off with -ocTCP_NODELAY=0 or -osTCP_NODELAY=0.
|
||||||
</p>
|
</p>
|
||||||
<p>
|
<p>
|
||||||
<b>Configuration examples:</b>
|
<b>Configuration examples:</b>
|
||||||
|
|||||||
@@ -656,16 +656,16 @@ iptables -t nat -A PREROUTING -p tcp -m multiport --dports 443,993,465 -j REDIRE
|
|||||||
<br>tlspr может использоваться как родительский прокси типа "tls" для реализации SNI-фрагментации (аналог NoDPI/GoodByeDPI).
|
<br>tlspr может использоваться как родительский прокси типа "tls" для реализации SNI-фрагментации (аналог NoDPI/GoodByeDPI).
|
||||||
Клиент отправляет первую часть TLS ClientHello, tlspr разбивает его на расширении SNI и отправляет двумя TCP-пакетами,
|
Клиент отправляет первую часть TLS ClientHello, tlspr разбивает его на расширении SNI и отправляет двумя TCP-пакетами,
|
||||||
что позволяет обойти некоторые DPI-системы, ищущие заблокированные имена хостов в TLS-рукопожатиях.
|
что позволяет обойти некоторые DPI-системы, ищущие заблокированные имена хостов в TLS-рукопожатиях.
|
||||||
<br>Для включения SNI break используйте <code>parent ... tls 0.0.0.0 0</code> и опцию <code>-s</code> на слушающем сервисе с TCP_NODELAY:
|
<br>Для включения SNI break используйте <code>parent ... tls 0.0.0.0 0</code> и опцию <code>-B</code> на слушающем сервисе:
|
||||||
</p><pre>
|
</p><pre>
|
||||||
auth iponly
|
auth iponly
|
||||||
allow *
|
allow *
|
||||||
parent 1000 tls 0.0.0.0 0
|
parent 1000 tls 0.0.0.0 0
|
||||||
allow *
|
allow *
|
||||||
proxy -s -i127.0.0.1 -ocTCP_NODELAY -osTCP_NODELAY -p1443
|
proxy -B -i127.0.0.1 -p1443
|
||||||
</pre>
|
</pre>
|
||||||
<p>
|
<p>
|
||||||
TCP_NODELAY необходим, чтобы ядро не объединяло разделенные пакеты.
|
TCP_NODELAY, установленный по умолчанию, необходим, чтобы ядро не объединяло разделенные пакеты: не отключайте его опциями -ocTCP_NODELAY=0 или -osTCP_NODELAY=0.
|
||||||
</p>
|
</p>
|
||||||
<p>
|
<p>
|
||||||
<b>Примеры конфигурации:</b>
|
<b>Примеры конфигурации:</b>
|
||||||
|
|||||||
@@ -245,6 +245,14 @@ delay GRACE_DELAY milliseconds before polling if average
|
|||||||
polling size is below GRACE_TRAFF bytes and GRACE_NUM read
|
polling size is below GRACE_TRAFF bytes and GRACE_NUM read
|
||||||
operations in a single direction are detected within 1
|
operations in a single direction are detected within 1
|
||||||
second. Useful to minimize polling <b><br>
|
second. Useful to minimize polling <b><br>
|
||||||
|
-B</b> (for TCP services) split the TLS ClientHello across
|
||||||
|
two TCP segments in the middle of the server name (SNI) when
|
||||||
|
it is passed through tlspr, as with <b>parent ... tls
|
||||||
|
0.0.0.0 0</b>: some DPI systems looking for blocked host
|
||||||
|
names do not reassemble it. TCP_NODELAY, set by default,
|
||||||
|
must not be turned off, or the kernel may join the segments
|
||||||
|
again. In builds without splice() <b>-s</b> does the same.
|
||||||
|
<b><br>
|
||||||
-s</b> <br>
|
-s</b> <br>
|
||||||
(for admin) secure, allow only secure operations, currently
|
(for admin) secure, allow only secure operations, currently
|
||||||
only traffic counters view without ability to reset. <br>
|
only traffic counters view without ability to reset. <br>
|
||||||
|
|||||||
@@ -230,15 +230,16 @@ a certificate (not compatible with TLS 1.3)</p></td></tr>
|
|||||||
<td width="4%">
|
<td width="4%">
|
||||||
|
|
||||||
|
|
||||||
<p><b>-s</b></p></td>
|
<p><b>-B</b></p></td>
|
||||||
<td width="5%"></td>
|
<td width="5%"></td>
|
||||||
<td width="82%">
|
<td width="82%">
|
||||||
|
|
||||||
|
|
||||||
<p>Split the TLS Client HELLO packet across multiple TCP
|
<p>Split the TLS Client HELLO packet across two TCP
|
||||||
segments to make SNI-based DPI detection harder. An optional
|
segments, in the middle of the SNI, to make SNI-based DPI
|
||||||
numeric value can follow (e.g. <b>-s1</b>) to control the
|
detection harder. In builds without splice() <b>-s</b> does
|
||||||
splitting behaviour.</p></td></tr>
|
the same; with splice() (Linux) <b>-s</b> is splice, see
|
||||||
|
<b>3proxy.cfg</b>(5).</p> </td></tr>
|
||||||
</table>
|
</table>
|
||||||
|
|
||||||
<p style="margin-left:9%;"><b>-Ximap | -Xpop3 |
|
<p style="margin-left:9%;"><b>-Ximap | -Xpop3 |
|
||||||
|
|||||||
@@ -198,6 +198,13 @@ any protocol-specific data.
|
|||||||
.B -g(\fIGRACE_TRAFF\fB,\fIGRACE_NUM\fB,\fIGRACE_DELAY\fR)
|
.B -g(\fIGRACE_TRAFF\fB,\fIGRACE_NUM\fB,\fIGRACE_DELAY\fR)
|
||||||
delay GRACE_DELAY milliseconds before polling if average polling size is below GRACE_TRAFF bytes and GRACE_NUM read operations in a single direction are detected within 1 second. Useful to minimize polling
|
delay GRACE_DELAY milliseconds before polling if average polling size is below GRACE_TRAFF bytes and GRACE_NUM read operations in a single direction are detected within 1 second. Useful to minimize polling
|
||||||
.br
|
.br
|
||||||
|
.B -B
|
||||||
|
(for TCP services) split the TLS ClientHello across two TCP segments in the
|
||||||
|
middle of the server name (SNI) when it is passed through tlspr, as with
|
||||||
|
\fBparent ... tls 0.0.0.0 0\fR: some DPI systems looking for blocked host names
|
||||||
|
do not reassemble it. TCP_NODELAY, set by default, must not be turned off, or the
|
||||||
|
kernel may join the segments again. In builds without splice() \fB-s\fR does the same.
|
||||||
|
.br
|
||||||
.B -s
|
.B -s
|
||||||
(for admin) secure, allow only secure operations, currently only traffic counters
|
(for admin) secure, allow only secure operations, currently only traffic counters
|
||||||
view without ability to reset.
|
view without ability to reset.
|
||||||
|
|||||||
+2
-2
@@ -76,8 +76,8 @@ destination_port. Port to establish outgoing connections. Required unless the Tr
|
|||||||
.B -c
|
.B -c
|
||||||
TLS_CHECK_LEVEL. 0 (default) - allow non-TLS traffic to pass, 1 - require TLS, only check client HELLO packet, 2 - require TLS, check both client and server HELLO, 3 - require TLS, check that the server sends a certificate (not compatible with TLS 1.3), 4 - require mutual TLS, check that the server sends a certificate request and the client sends a certificate (not compatible with TLS 1.3)
|
TLS_CHECK_LEVEL. 0 (default) - allow non-TLS traffic to pass, 1 - require TLS, only check client HELLO packet, 2 - require TLS, check both client and server HELLO, 3 - require TLS, check that the server sends a certificate (not compatible with TLS 1.3), 4 - require mutual TLS, check that the server sends a certificate request and the client sends a certificate (not compatible with TLS 1.3)
|
||||||
.TP
|
.TP
|
||||||
.B -s
|
.B -B
|
||||||
Split the TLS Client HELLO packet across multiple TCP segments to make SNI-based DPI detection harder. An optional numeric value can follow (e.g. \fB-s1\fR) to control the splitting behaviour.
|
Split the TLS Client HELLO packet across two TCP segments, in the middle of the SNI, to make SNI-based DPI detection harder. In builds without splice() \fB-s\fR does the same; with splice() (Linux) \fB-s\fR is splice, see \fB3proxy.cfg\fR(5).
|
||||||
.TP
|
.TP
|
||||||
.B -Ximap | -Xpop3 | -Xsmtp
|
.B -Ximap | -Xpop3 | -Xsmtp
|
||||||
STARTTLS mode for the given protocol. The proxy speaks the plaintext protocol
|
STARTTLS mode for the given protocol. The proxy speaks the plaintext protocol
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
Name: 3proxy
|
Name: 3proxy
|
||||||
Version: 1.0.2
|
Version: 1.0.4
|
||||||
Release: 1%{?dist}
|
Release: 1%{?dist}
|
||||||
Summary: 3proxy tiny proxy server
|
Summary: 3proxy tiny proxy server
|
||||||
License: GPL/LGPL/Apache/BSD
|
License: GPL/LGPL/Apache/BSD
|
||||||
|
|||||||
+21
-11
@@ -382,6 +382,21 @@ void cyclestep(void){
|
|||||||
#define RETURN(x) {res = x; goto CLEARRETURN;}
|
#define RETURN(x) {res = x; goto CLEARRETURN;}
|
||||||
|
|
||||||
|
|
||||||
|
static void printusage(struct extparam *cconf, int argc, char * argv[]){
|
||||||
|
|
||||||
|
fprintf(stderr, "Usage: %s [conffile]\n", argv[0]);
|
||||||
|
#ifdef _WIN32
|
||||||
|
fprintf(stderr, "\n\t%s --install [conffile]\n\tto install as service\n"
|
||||||
|
"\n\t%s --remove\n\tto remove service\n", argv[0], argv[0]);
|
||||||
|
#else
|
||||||
|
fprintf(stderr, "\n if conffile is missing, configuration is expected from stdin\n");
|
||||||
|
#endif
|
||||||
|
fprintf(stderr, "\n\t%s --help\n\tthis message\n", argv[0]);
|
||||||
|
fprintf(stderr, "available socket options:\n\t%s\n", printopts("\n\t"));
|
||||||
|
fprintf(stderr, "built with:\n\t%s\n", printfeatures("\n\t"));
|
||||||
|
fprintf(stderr, "\n%s %s\n%s\n", cconf->stringtable[2], cconf->stringtable[3], copyright);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
#ifndef _WINCE
|
#ifndef _WINCE
|
||||||
int main(int argc, char * argv[]) {
|
int main(int argc, char * argv[]) {
|
||||||
@@ -424,6 +439,10 @@ int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
conf.stringtable = strings;
|
conf.stringtable = strings;
|
||||||
|
if(argc == 2 && (!strcmp((char *)argv[1], "--help") || !strcmp((char *)argv[1], "-h"))) {
|
||||||
|
printusage(&conf, argc, argv);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
#ifdef _WIN32
|
#ifdef _WIN32
|
||||||
#ifndef _WINCE
|
#ifndef _WINCE
|
||||||
if((argc == 2 || argc == 3)&& !strcmp((char *)argv[1], "--install")) {
|
if((argc == 2 || argc == 3)&& !strcmp((char *)argv[1], "--install")) {
|
||||||
@@ -536,18 +555,9 @@ int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int
|
|||||||
}
|
}
|
||||||
if(argc > 2 || !(fp)) {
|
if(argc > 2 || !(fp)) {
|
||||||
|
|
||||||
fprintf(stderr, "Usage: %s [conffile]\n", argv[0]);
|
printusage(&conf, argc, argv);
|
||||||
#ifdef _WIN32
|
|
||||||
fprintf(stderr, "\n\t%s --install [conffile]\n\tto install as service\n"
|
|
||||||
"\n\t%s --remove\n\tto remove service\n", argv[0], argv[0]);
|
|
||||||
#else
|
|
||||||
fprintf(stderr, "\n if conffile is missing, configuration is expected from stdin\n");
|
|
||||||
#endif
|
|
||||||
fprintf(stderr, "available socket options:\n\t%s\n", printopts("\n\t"));
|
|
||||||
fprintf(stderr, "\n%s %s\n%s\n", conf.stringtable[2], conf.stringtable[3], copyright);
|
|
||||||
|
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
#ifndef _WIN32
|
#ifndef _WIN32
|
||||||
/* before readconfig() starts the services: a client gone while it is
|
/* before readconfig() starts the services: a client gone while it is
|
||||||
|
|||||||
+4
-1
@@ -125,7 +125,10 @@ int doauth(struct clientparam * param){
|
|||||||
if(authfuncs->authorize &&
|
if(authfuncs->authorize &&
|
||||||
(res = (*authfuncs->authorize)(param)))
|
(res = (*authfuncs->authorize)(param)))
|
||||||
return res;
|
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=""};
|
struct authcache ac={.username=""};
|
||||||
|
|
||||||
if(param->username) {
|
if(param->username) {
|
||||||
|
|||||||
+23
-4
@@ -198,12 +198,20 @@ static int calc_replydigest(char *packet, char *original, const char *secret, in
|
|||||||
int secretlen;
|
int secretlen;
|
||||||
uint8_t calc_digest[AUTH_VECTOR_LEN];
|
uint8_t calc_digest[AUTH_VECTOR_LEN];
|
||||||
uint8_t calc_vector[AUTH_VECTOR_LEN];
|
uint8_t calc_vector[AUTH_VECTOR_LEN];
|
||||||
|
unsigned int dlen = AUTH_VECTOR_LEN;
|
||||||
|
mdh_ctx *ctx;
|
||||||
|
|
||||||
memcpy(calc_vector, packet + 4, AUTH_VECTOR_LEN);
|
memcpy(calc_vector, packet + 4, AUTH_VECTOR_LEN);
|
||||||
memcpy(packet + 4, original, AUTH_VECTOR_LEN);
|
memcpy(packet + 4, original, AUTH_VECTOR_LEN);
|
||||||
secretlen = strlen(secret);
|
secretlen = strlen(secret);
|
||||||
memcpy(packet + len, secret, secretlen);
|
/* hash the reply, then the secret: nothing is written past the reply */
|
||||||
md5_calc(calc_digest, (u_char *)packet, len + secretlen);
|
if(!(ctx = mdh_init(MDH_MD5, 16))) return 2;
|
||||||
|
if(!mdh_update(ctx, packet, len) || !mdh_update(ctx, secret, secretlen) ||
|
||||||
|
!mdh_final(ctx, calc_digest, &dlen)) {
|
||||||
|
mdh_free(ctx);
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
mdh_free(ctx);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Return 0 if OK, 2 if not OK.
|
* Return 0 if OK, 2 if not OK.
|
||||||
@@ -298,6 +306,7 @@ int radsend(struct clientparam * param, int auth, int stop){
|
|||||||
int total_length;
|
int total_length;
|
||||||
int len;
|
int len;
|
||||||
PROXYSOCKADDRTYPE saremote;
|
PROXYSOCKADDRTYPE saremote;
|
||||||
|
PROXYSOCKADDRTYPE safrom;
|
||||||
struct pollfd fds[1];
|
struct pollfd fds[1];
|
||||||
char vector[AUTH_VECTOR_LEN];
|
char vector[AUTH_VECTOR_LEN];
|
||||||
radius_packet_t packet, rpacket;
|
radius_packet_t packet, rpacket;
|
||||||
@@ -568,15 +577,25 @@ int radsend(struct clientparam * param, int auth, int stop){
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
salen = sizeof(saremote);
|
salen = sizeof(safrom);
|
||||||
|
|
||||||
data_len = so._recvfrom(so.state, remsock, (char *)&rpacket, sizeof(packet)-16,
|
data_len = so._recvfrom(so.state, remsock, (char *)&rpacket, sizeof(packet)-16,
|
||||||
0, (struct sockaddr *)&saremote, &salen);
|
0, (struct sockaddr *)&safrom, &salen);
|
||||||
|
|
||||||
|
|
||||||
if (data_len < 20) {
|
if (data_len < 20) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
/* the reply must come from the server we asked */
|
||||||
|
if(*SAFAMILY(&safrom) != *SAFAMILY(&saremote) ||
|
||||||
|
memcmp(SAADDR(&safrom), SAADDR(&saremote), SAADDRLEN(&saremote)) ||
|
||||||
|
*SAPORT(&safrom) != *SAPORT(&saremote)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
/* and answer this request, and be of its own length */
|
||||||
|
if(data_len != ntohs(rpacket.length) || rpacket.id != packet.id) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
if( auth && rpacket.code != PW_AUTHENTICATION_ACK &&
|
if( auth && rpacket.code != PW_AUTHENTICATION_ACK &&
|
||||||
rpacket.code != PW_AUTHENTICATION_REJECT ){
|
rpacket.code != PW_AUTHENTICATION_REJECT ){
|
||||||
|
|||||||
@@ -542,11 +542,26 @@ int parsehost(int family, unsigned char *host, struct sockaddr *sa){
|
|||||||
return ret;
|
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){
|
int parsehostname(char *hostname, struct clientparam *param, uint16_t port){
|
||||||
char *sp=NULL,*se=NULL;
|
char *sp=NULL,*se=NULL;
|
||||||
int ret = 0;
|
int ret = 0;
|
||||||
|
|
||||||
if(!hostname || !*hostname)return 2;
|
if(!hostname || !*hostname)return 2;
|
||||||
|
if(badhostname(hostname)) return 1;
|
||||||
if(*hostname == '[') se=strchr(hostname, ']');
|
if(*hostname == '[') se=strchr(hostname, ']');
|
||||||
if ((sp = strchr(se?se:hostname, ':'))) {
|
if ((sp = strchr(se?se:hostname, ':'))) {
|
||||||
if(strchr(sp+1, ':'))sp = NULL;
|
if(strchr(sp+1, ':'))sp = NULL;
|
||||||
@@ -560,6 +575,9 @@ int parsehostname(char *hostname, struct clientparam *param, uint16_t port){
|
|||||||
port = atoi(sp+1);
|
port = atoi(sp+1);
|
||||||
*sp = ':';
|
*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(¶m->req) = htons(port);
|
*SAPORT(¶m->req) = htons(port);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
@@ -634,6 +652,26 @@ int parseconnusername(char *username, struct clientparam *param, int extpasswd,
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* What waits for a socket waits in poll(): a call on it never does. */
|
||||||
|
void nonblock(SOCKET sock){
|
||||||
|
#ifdef _WIN32
|
||||||
|
unsigned long ul = 1;
|
||||||
|
ioctlsocket(sock, FIONBIO, &ul);
|
||||||
|
#else
|
||||||
|
fcntl(sock, F_SETFL, O_NONBLOCK | fcntl(sock, F_GETFL));
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
/* accept() with nothing to accept: another took it, or it was gone */
|
||||||
|
int acceptagain(void){
|
||||||
|
#ifdef _WIN32
|
||||||
|
int err = WSAGetLastError();
|
||||||
|
return err == WSAEWOULDBLOCK || err == WSAECONNRESET || err == WSAEINTR;
|
||||||
|
#else
|
||||||
|
return errno == EAGAIN || errno == EWOULDBLOCK || errno == ECONNABORTED || errno == EINTR;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
int connectwithpoll(struct clientparam *param, SOCKET sock, struct sockaddr *sa, SASIZETYPE size, int to){
|
int connectwithpoll(struct clientparam *param, SOCKET sock, struct sockaddr *sa, SASIZETYPE size, int to){
|
||||||
struct pollfd fds[1];
|
struct pollfd fds[1];
|
||||||
#ifdef _WIN32
|
#ifdef _WIN32
|
||||||
@@ -760,6 +798,22 @@ int doconnect(struct clientparam * param){
|
|||||||
param->srv->so._setsockopt(param->sostate, param->remsock, SOL_SOCKET, SO_LINGER, (char *)&lg, sizeof(lg));
|
param->srv->so._setsockopt(param->sostate, param->remsock, SOL_SOCKET, SO_LINGER, (char *)&lg, sizeof(lg));
|
||||||
#endif
|
#endif
|
||||||
if(extbindtodevice(param, param->remsock)) return 12;
|
if(extbindtodevice(param, param->remsock)) return 12;
|
||||||
|
#ifdef IP_BIND_ADDRESS_NO_PORT
|
||||||
|
/* A port the kernel chooses is chosen by connect(), for the pair with
|
||||||
|
the destination: one in use towards another destination, or closing
|
||||||
|
from an earlier connection, does as well. bind() would take one of
|
||||||
|
its own, and with many connections find none left, or search long
|
||||||
|
for it. */
|
||||||
|
if((param->operation >= 256 || (param->operation & CONNECT) || param->redirected)
|
||||||
|
# ifdef WITH_UN
|
||||||
|
&& *SAFAMILY(¶m->sinsl) != AF_UNIX
|
||||||
|
# endif
|
||||||
|
){
|
||||||
|
int one = 1;
|
||||||
|
|
||||||
|
param->srv->so._setsockopt(param->sostate, param->remsock, IPPROTO_IP, IP_BIND_ADDRESS_NO_PORT, (char *)&one, sizeof(one));
|
||||||
|
}
|
||||||
|
#endif
|
||||||
#ifdef WITH_UN
|
#ifdef WITH_UN
|
||||||
if(*SAFAMILY(¶m->sinsl) != AF_UNIX)
|
if(*SAFAMILY(¶m->sinsl) != AF_UNIX)
|
||||||
#endif
|
#endif
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ int ftplogin(struct clientparam *param, char *nbuf, int *innbuf) {
|
|||||||
if(i < 3) return 706;
|
if(i < 3) return 706;
|
||||||
buf[i] = 0;
|
buf[i] = 0;
|
||||||
if(atoi(buf)/100 != 2) {
|
if(atoi(buf)/100 != 2) {
|
||||||
*innbuf = i;
|
if(innbuf)*innbuf = i;
|
||||||
return 702;
|
return 702;
|
||||||
}
|
}
|
||||||
sprintf(buf, "USER %.128s\r\n", param->extusername?param->extusername:(unsigned char *)"anonymous");
|
sprintf(buf, "USER %.128s\r\n", param->extusername?param->extusername:(unsigned char *)"anonymous");
|
||||||
@@ -77,6 +77,9 @@ int ftplogin(struct clientparam *param, char *nbuf, int *innbuf) {
|
|||||||
return 701;
|
return 701;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
/* USER answered at once, logged in (230) or refused: that answer is
|
||||||
|
the client's, waiting for one to its PASS */
|
||||||
|
else if(innbuf)*innbuf = i;
|
||||||
if(res != 2) {
|
if(res != 2) {
|
||||||
return 700;
|
return 700;
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -132,7 +132,7 @@ void * ftpprchild(struct clientparam* param) {
|
|||||||
param->srv->so._closesocket(param->sostate, clidatasock);
|
param->srv->so._closesocket(param->sostate, clidatasock);
|
||||||
clidatasock = INVALID_SOCKET;
|
clidatasock = INVALID_SOCKET;
|
||||||
}
|
}
|
||||||
if ((clidatasock=socket(SASOCK(¶m->sincl), SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) {RETURN(821);}
|
if ((clidatasock=param->srv->so._socket(param->sostate, SASOCK(¶m->sincl), SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) {RETURN(821);}
|
||||||
if(intbindtodevice(param, clidatasock)){RETURN(822);}
|
if(intbindtodevice(param, clidatasock)){RETURN(822);}
|
||||||
*SAPORT(¶m->sincl) = 0;
|
*SAPORT(¶m->sincl) = 0;
|
||||||
if(bindwithrange(param, clidatasock, ¶m->sincl, param->intport)){RETURN(822);}
|
if(bindwithrange(param, clidatasock, ¶m->sincl, param->intport)){RETURN(822);}
|
||||||
|
|||||||
+35
-6
@@ -430,11 +430,12 @@ static int targetunsafe(const char *path)
|
|||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
if(!strncmp(path, "./", 2) || !strncmp(path, "../", 3)) return 1;
|
if(!strncmp(path, "./", 2) || !strncmp(path, "../", 3)) return 1;
|
||||||
if(strstr(path, "/./") || strstr(path, "/../")) return 1;
|
/* a dot-dot segment, with either separator, wherever it is in the
|
||||||
if(strstr(path, "\\.\\") || strstr(path, "\\..\\")) return 1;
|
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);
|
p = path + strlen(path);
|
||||||
if(p - path >= 2 && !strcmp(p - 2, "/.")) return 1;
|
if(p - path >= 2 && (!strcmp(p - 2, "/.") || !strcmp(p - 2, "\\."))) return 1;
|
||||||
if(p - path >= 3 && !strcmp(p - 3, "/..")) return 1;
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1495,16 +1496,27 @@ static int httpsrv_request(struct clientparam *param, struct httpreq *r)
|
|||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if(i && i != 10){
|
if(i){
|
||||||
/* The body goes before the answer, as for any answer this server
|
/* 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. */
|
gives: left in the stream it would be read as the next request. */
|
||||||
if(!r->drained){
|
if(!r->drained){
|
||||||
if(r->contentlen) httpsrv_drain(param, r->contentlen);
|
if(r->contentlen) httpsrv_drain(param, r->contentlen);
|
||||||
r->drained = 1;
|
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
|
/* 4 no credentials, 5 unknown user, 6 wrong password: all of them
|
||||||
should let the client offer credentials again. */
|
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);
|
else op_forbidden(r);
|
||||||
RETURN(i);
|
RETURN(i);
|
||||||
}
|
}
|
||||||
@@ -1606,6 +1618,23 @@ void * httpsrvchild(struct clientparam *param)
|
|||||||
r.lasthost = lasthost;
|
r.lasthost = lasthost;
|
||||||
param->res = 0;
|
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);
|
answered = httpsrv_request(param, &r);
|
||||||
handoff = r.handoff;
|
handoff = r.handoff;
|
||||||
if(r.raw) free(r.raw);
|
if(r.raw) free(r.raw);
|
||||||
|
|||||||
+42
-12
@@ -220,6 +220,14 @@ struct pcre_filter_data {
|
|||||||
struct ace *acl;
|
struct ace *acl;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/* What a connection matches with: pcre2_match() writes into its match
|
||||||
|
data, so a thread matching on the rule's own one would race every
|
||||||
|
other thread doing the same. */
|
||||||
|
struct pcre_client_data {
|
||||||
|
struct pcre_filter_data *pcrefd;
|
||||||
|
pcre2_match_data * match_data;
|
||||||
|
};
|
||||||
|
|
||||||
static void pcre_data_free(struct pcre_filter_data *pcrefd){
|
static void pcre_data_free(struct pcre_filter_data *pcrefd){
|
||||||
_3proxy_mutex_lock(&pcre_mutex);
|
_3proxy_mutex_lock(&pcre_mutex);
|
||||||
pcrefd->users--;
|
pcrefd->users--;
|
||||||
@@ -253,16 +261,31 @@ static void* pcre_filter_open(void * idata, struct srvparam * param){
|
|||||||
static FILTER_ACTION pcre_filter_client(void *fo, struct clientparam * param, void** fc){
|
static FILTER_ACTION pcre_filter_client(void *fo, struct clientparam * param, void** fc){
|
||||||
int res;
|
int res;
|
||||||
struct ace tmpace;
|
struct ace tmpace;
|
||||||
|
struct pcre_filter_data *rule = (struct pcre_filter_data *)fo;
|
||||||
|
struct pcre_client_data *pcd;
|
||||||
|
|
||||||
*fc = fo;
|
*fc = NULL;
|
||||||
if(!fo) return PASS;
|
if(!fo) return PASS;
|
||||||
#define pcrefd ((struct pcre_filter_data *)fo)
|
if(rule->acl){
|
||||||
if(!pcrefd->acl) return CONTINUE;
|
memset (&tmpace, 0, sizeof(struct ace));
|
||||||
memset (&tmpace, 0, sizeof(struct ace));
|
tmpace.src = rule->acl->src;
|
||||||
tmpace.src = pcrefd->acl->src;
|
res = pl->ACLMatches(&tmpace, param);
|
||||||
res = pl->ACLMatches(&tmpace, param);
|
if(!res) return PASS;
|
||||||
#undef pcrefd
|
}
|
||||||
return (res)? CONTINUE:PASS;
|
/* the connection goes on with a match data of its own */
|
||||||
|
if(!(pcd = pl->mallocfunc(sizeof(struct pcre_client_data)))){
|
||||||
|
*fc = NULL;
|
||||||
|
return rule->action;
|
||||||
|
}
|
||||||
|
pcd->pcrefd = rule;
|
||||||
|
pcd->match_data = NULL;
|
||||||
|
if(rule->re && !(pcd->match_data = pcre2_match_data_create_from_pattern(rule->re, NULL))){
|
||||||
|
pl->freefunc(pcd);
|
||||||
|
*fc = NULL;
|
||||||
|
return rule->action;
|
||||||
|
}
|
||||||
|
*fc = pcd;
|
||||||
|
return CONTINUE;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* What a rewritten buffer keeps free for its caller to append to. */
|
/* What a rewritten buffer keeps free for its caller to append to. */
|
||||||
@@ -277,7 +300,8 @@ static FILTER_ACTION pcre_filter_buffer(void *fc, struct clientparam *param, uns
|
|||||||
char * replace;
|
char * replace;
|
||||||
char * tmpbuf, *target, *newbuf;
|
char * tmpbuf, *target, *newbuf;
|
||||||
int nreplaces=0;
|
int nreplaces=0;
|
||||||
#define pcrefd ((struct pcre_filter_data *)fc)
|
struct pcre_client_data *pcd = (struct pcre_client_data *)fc;
|
||||||
|
#define pcrefd (pcd->pcrefd)
|
||||||
|
|
||||||
for(acl = pcrefd->acl; acl; acl=acl->next){
|
for(acl = pcrefd->acl; acl; acl=acl->next){
|
||||||
if(pl->ACLMatches(acl, param)){
|
if(pl->ACLMatches(acl, param)){
|
||||||
@@ -290,9 +314,9 @@ static FILTER_ACTION pcre_filter_buffer(void *fc, struct clientparam *param, uns
|
|||||||
for(; offset < *length_p; nreplaces++){
|
for(; offset < *length_p; nreplaces++){
|
||||||
int repsz;
|
int repsz;
|
||||||
|
|
||||||
count = pcre2_match(pcrefd->re, (PCRE2_SPTR)*buf_p, *length_p, offset, 0, pcrefd->match_data, pcrefd->match_context);
|
count = pcre2_match(pcrefd->re, (PCRE2_SPTR)*buf_p, *length_p, offset, 0, pcd->match_data, pcrefd->match_context);
|
||||||
if(count <= 0) break;
|
if(count <= 0) break;
|
||||||
ovector = pcre2_get_ovector_pointer(pcrefd->match_data);
|
ovector = pcre2_get_ovector_pointer(pcd->match_data);
|
||||||
if(ovector[0] > (PCRE2_SIZE)*length_p || ovector[1] > (PCRE2_SIZE)*length_p || ovector[1] < ovector[0]) break;
|
if(ovector[0] > (PCRE2_SIZE)*length_p || ovector[1] > (PCRE2_SIZE)*length_p || ovector[1] < ovector[0]) break;
|
||||||
if(!(replace = pcrefd->replace) || param->nooverwritefilter) return pcrefd->action;
|
if(!(replace = pcrefd->replace) || param->nooverwritefilter) return pcrefd->action;
|
||||||
|
|
||||||
@@ -376,7 +400,13 @@ static FILTER_ACTION pcre_filter_buffer(void *fc, struct clientparam *param, uns
|
|||||||
#undef pcrefd
|
#undef pcrefd
|
||||||
}
|
}
|
||||||
|
|
||||||
static void pcre_filter_clear(void *fo){
|
static void pcre_filter_clear(void *fc){
|
||||||
|
struct pcre_client_data *pcd = (struct pcre_client_data *)fc;
|
||||||
|
|
||||||
|
if(pcd){
|
||||||
|
if(pcd->match_data) pcre2_match_data_free(pcd->match_data);
|
||||||
|
pl->freefunc(pcd);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static void pcre_filter_close(void *fo){
|
static void pcre_filter_close(void *fo){
|
||||||
|
|||||||
@@ -286,7 +286,7 @@ void processcallbacks(struct fp_stream *fps, int what, char *msg, int size){
|
|||||||
case GOT_SMTP_REQ:
|
case GOT_SMTP_REQ:
|
||||||
case GOT_SMTP_DATA:
|
case GOT_SMTP_DATA:
|
||||||
fps->state = FLUSH_DATA;
|
fps->state = FLUSH_DATA;
|
||||||
pl->socksend(fps->fpd.cp->sostate,fps->fpd.cp->clisock, (unsigned char *)fp_stringtable[1], (int)strlen((char *)fp_stringtable[1]), pl->conf->timeouts[STRING_S]);
|
pl->socksend(NULL, fps->fpd.cp->clisock, (unsigned char *)fp_stringtable[1], (int)strlen((char *)fp_stringtable[1]), pl->conf->timeouts[STRING_S]);
|
||||||
fps->state = state;
|
fps->state = state;
|
||||||
break;
|
break;
|
||||||
case GOT_HTTP_REQUEST:
|
case GOT_HTTP_REQUEST:
|
||||||
@@ -298,7 +298,7 @@ void processcallbacks(struct fp_stream *fps, int what, char *msg, int size){
|
|||||||
case GOT_HTTP_SRVDATA:
|
case GOT_HTTP_SRVDATA:
|
||||||
if(!fps->serversent){
|
if(!fps->serversent){
|
||||||
fps->state = FLUSH_DATA;
|
fps->state = FLUSH_DATA;
|
||||||
pl->socksend(fps->fpd.cp->sostate, fps->fpd.cp->clisock, (unsigned char *)fp_stringtable[0], (int)strlen((char *)fp_stringtable[0]), pl->conf->timeouts[STRING_S]);
|
pl->socksend(NULL, fps->fpd.cp->clisock, (unsigned char *)fp_stringtable[0], (int)strlen((char *)fp_stringtable[0]), pl->conf->timeouts[STRING_S]);
|
||||||
fps->state = state;
|
fps->state = state;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
@@ -306,7 +306,7 @@ void processcallbacks(struct fp_stream *fps, int what, char *msg, int size){
|
|||||||
case GOT_FTP_REQ:
|
case GOT_FTP_REQ:
|
||||||
case GOT_FTP_SRVDATA:
|
case GOT_FTP_SRVDATA:
|
||||||
fps->state = FLUSH_DATA;
|
fps->state = FLUSH_DATA;
|
||||||
pl->socksend(fps->fpd.cp->sostate, fps->fpd.cp->ctrlsock, (unsigned char *)fp_stringtable[1], (int)strlen((char *)fp_stringtable[1]), pl->conf->timeouts[STRING_S]);
|
pl->socksend(NULL, fps->fpd.cp->ctrlsock, (unsigned char *)fp_stringtable[1], (int)strlen((char *)fp_stringtable[1]), pl->conf->timeouts[STRING_S]);
|
||||||
fps->state = state;
|
fps->state = state;
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
@@ -358,7 +358,7 @@ static int copyfdtosock(struct fp_stream * fps, DIRECTION which, long len){
|
|||||||
if(fps->serversent >= fps->srvhdrwritten){
|
if(fps->serversent >= fps->srvhdrwritten){
|
||||||
sprintf(fps->buf, "%lx\r\n", len);
|
sprintf(fps->buf, "%lx\r\n", len);
|
||||||
sendchunk = (int)strlen(fps->buf);
|
sendchunk = (int)strlen(fps->buf);
|
||||||
if(pl->socksend(fps->fpd.cp->sostate, fps->fpd.cp->clisock, (unsigned char *)fps->buf, sendchunk, pl->conf->timeouts[STRING_S]) != sendchunk){
|
if(pl->socksend(NULL, fps->fpd.cp->clisock, (unsigned char *)fps->buf, sendchunk, pl->conf->timeouts[STRING_S]) != sendchunk){
|
||||||
return -4;
|
return -4;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -397,13 +397,13 @@ static int copyfdtosock(struct fp_stream * fps, DIRECTION which, long len){
|
|||||||
#endif
|
#endif
|
||||||
return -3;
|
return -3;
|
||||||
}
|
}
|
||||||
if(pl->socksend(fps->fpd.cp->sostate, sock, (unsigned char *)fps->buf, res, pl->conf->timeouts[STRING_S]) != res) {
|
if(pl->socksend(NULL, sock, (unsigned char *)fps->buf, res, pl->conf->timeouts[STRING_S]) != res) {
|
||||||
return -4;
|
return -4;
|
||||||
}
|
}
|
||||||
len -= res;
|
len -= res;
|
||||||
}
|
}
|
||||||
if(sendchunk){
|
if(sendchunk){
|
||||||
if(pl->socksend(fps->fpd.cp->sostate, sock, (unsigned char *)"\r\n", 2, pl->conf->timeouts[STRING_S]) != 2)
|
if(pl->socksend(NULL, sock, (unsigned char *)"\r\n", 2, pl->conf->timeouts[STRING_S]) != 2)
|
||||||
return -4;
|
return -4;
|
||||||
}
|
}
|
||||||
fps->state = state;
|
fps->state = state;
|
||||||
|
|||||||
@@ -61,14 +61,9 @@ char **load_string(FILE *f,int max_count_str, int *countloadstr,
|
|||||||
|
|
||||||
if (strstr(tmpbuf1,"[end]")==NULL)
|
if (strstr(tmpbuf1,"[end]")==NULL)
|
||||||
{
|
{
|
||||||
/* find and replace \n \r*/
|
/* the line's end cut off: what the file says with \n is what is
|
||||||
rstr = tmpbuf1;
|
sent */
|
||||||
while (*rstr!='\0')
|
tmpbuf1[strcspn(tmpbuf1, "\r\n")] = '\0';
|
||||||
{
|
|
||||||
if (*rstr=='\r' || *rstr=='\n' )
|
|
||||||
{ *rstr='\0'; rstr++; }
|
|
||||||
rstr++;
|
|
||||||
}
|
|
||||||
|
|
||||||
while ((rstr=strstr(tmpbuf1,"\\n")))
|
while ((rstr=strstr(tmpbuf1,"\\n")))
|
||||||
{
|
{
|
||||||
|
|||||||
+21
@@ -340,6 +340,27 @@ for(;;){
|
|||||||
clhdrofs_req = -1;
|
clhdrofs_req = -1;
|
||||||
param->nolongdatfilter = 0;
|
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
|
/* A connection waiting a while for its next request, or a tunnel, holds
|
||||||
no buffer: it is taken again once a request starts coming. */
|
no buffer: it is taken again once a request starts coming. */
|
||||||
if(buf && param->cliinbuf == param->clioffset){
|
if(buf && param->cliinbuf == param->clioffset){
|
||||||
|
|||||||
+6
-1
@@ -191,7 +191,8 @@ size_t threadstacksize(int extra);
|
|||||||
#ifndef strncasecmp
|
#ifndef strncasecmp
|
||||||
#define strncasecmp strnicmp
|
#define strncasecmp strnicmp
|
||||||
#endif
|
#endif
|
||||||
#define seterrno3(x) _set_errno(x)
|
/* errno is WSAGetLastError() here */
|
||||||
|
#define seterrno3(x) WSASetLastError(x)
|
||||||
#else
|
#else
|
||||||
#define seterrno3(x) (errno = x)
|
#define seterrno3(x) (errno = x)
|
||||||
#endif
|
#endif
|
||||||
@@ -369,6 +370,7 @@ void hashdelete(struct hashtable *ht, void* name);
|
|||||||
int hashresolv(struct hashtable *ht, void* name, void* value, uint32_t *ttl);
|
int hashresolv(struct hashtable *ht, void* name, void* value, uint32_t *ttl);
|
||||||
|
|
||||||
int parsehost(int family, unsigned char *host, struct sockaddr *sa);
|
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 parsehostname(char *hostname, struct clientparam *param, uint16_t port);
|
||||||
int parseusername(char *username, struct clientparam *param, int extpasswd);
|
int parseusername(char *username, struct clientparam *param, int extpasswd);
|
||||||
int parseconnusername(char *username, struct clientparam *param, int extpasswd, uint16_t port);
|
int parseconnusername(char *username, struct clientparam *param, int extpasswd, uint16_t port);
|
||||||
@@ -405,6 +407,8 @@ unsigned char * dologname (unsigned char *buf, unsigned char *name, const unsign
|
|||||||
int readconfig(FILE * fp);
|
int readconfig(FILE * fp);
|
||||||
void initcommands(void);
|
void initcommands(void);
|
||||||
int connectwithpoll(struct clientparam *param, SOCKET sock, struct sockaddr *sa, SASIZETYPE size, int to);
|
int connectwithpoll(struct clientparam *param, SOCKET sock, struct sockaddr *sa, SASIZETYPE size, int to);
|
||||||
|
void nonblock(SOCKET sock);
|
||||||
|
int acceptagain(void);
|
||||||
int bindwithrange(struct clientparam *param, SOCKET sock, PROXYSOCKADDRTYPE *sa, uint32_t range);
|
int bindwithrange(struct clientparam *param, SOCKET sock, PROXYSOCKADDRTYPE *sa, uint32_t range);
|
||||||
int bindtodevice(struct sockfuncs *sf, void *state, SOCKET sock, const char *device, int family);
|
int bindtodevice(struct sockfuncs *sf, void *state, SOCKET sock, const char *device, int family);
|
||||||
int extbindtodevice(struct clientparam *param, SOCKET sock);
|
int extbindtodevice(struct clientparam *param, SOCKET sock);
|
||||||
@@ -509,6 +513,7 @@ extern struct socketoptions {
|
|||||||
int getopts(const char *s, struct sockoptset *opts);
|
int getopts(const char *s, struct sockoptset *opts);
|
||||||
void setopts(SOCKET s, const struct sockoptset *opts);
|
void setopts(SOCKET s, const struct sockoptset *opts);
|
||||||
char * printopts(char *sep);
|
char * printopts(char *sep);
|
||||||
|
char * printfeatures(char *sep);
|
||||||
|
|
||||||
#ifdef _WINCE
|
#ifdef _WINCE
|
||||||
char * CEToUnicode (const char *str);
|
char * CEToUnicode (const char *str);
|
||||||
|
|||||||
@@ -63,6 +63,8 @@ void * threadfunc (void *p) {
|
|||||||
}
|
}
|
||||||
param->remsock = param->srv->so._accept(param->sostate, param->srv->cbsock, (struct sockaddr*)¶m->sinsr, &size);
|
param->remsock = param->srv->so._accept(param->sostate, param->srv->cbsock, (struct sockaddr*)¶m->sinsr, &size);
|
||||||
if(param->remsock == INVALID_SOCKET) {
|
if(param->remsock == INVALID_SOCKET) {
|
||||||
|
/* another client of the service took it: not a try */
|
||||||
|
if(acceptagain()) { i++; continue; }
|
||||||
dolog(param, (unsigned char *)"Connect back accept() failed");
|
dolog(param, (unsigned char *)"Connect back accept() failed");
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -224,6 +226,69 @@ char * printopts(char *sep){
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
char featsbuf[1024];
|
||||||
|
|
||||||
|
/* The features of this build, by the names the manual and the test suite
|
||||||
|
know them, so a user can see what a binary was made with. */
|
||||||
|
char * printfeatures(char *sep){
|
||||||
|
int pos=0;
|
||||||
|
|
||||||
|
#define ADDFEATURE(x) pos += sprintf(featsbuf+pos,"%s%s",pos?sep:"",x)
|
||||||
|
#ifdef WITH_SSL
|
||||||
|
ADDFEATURE("ssl");
|
||||||
|
#ifdef WITH_WOLFSSL
|
||||||
|
ADDFEATURE("wolfssl");
|
||||||
|
#else
|
||||||
|
ADDFEATURE("openssl");
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
#ifndef NORADIUS
|
||||||
|
ADDFEATURE("radius");
|
||||||
|
#endif
|
||||||
|
#ifdef WITH_PCRE
|
||||||
|
ADDFEATURE("pcre");
|
||||||
|
#endif
|
||||||
|
#ifndef NOIPV6
|
||||||
|
ADDFEATURE("ipv6");
|
||||||
|
#endif
|
||||||
|
#ifdef WITH_UN
|
||||||
|
ADDFEATURE("unix");
|
||||||
|
#endif
|
||||||
|
#ifdef WITH_HTTPSRV
|
||||||
|
ADDFEATURE("httpsrv");
|
||||||
|
#endif
|
||||||
|
#ifdef WITH_TRANSPARENT
|
||||||
|
ADDFEATURE("transparent");
|
||||||
|
#endif
|
||||||
|
#ifdef WITH_NETFILTER
|
||||||
|
ADDFEATURE("netfilter");
|
||||||
|
#endif
|
||||||
|
#ifdef WITH_PF
|
||||||
|
ADDFEATURE("pf");
|
||||||
|
#endif
|
||||||
|
#ifdef WITH_ODBC
|
||||||
|
ADDFEATURE("odbc");
|
||||||
|
#endif
|
||||||
|
#ifdef WITH_FTP
|
||||||
|
ADDFEATURE("ftppr");
|
||||||
|
#endif
|
||||||
|
#ifdef WITH_POP3P
|
||||||
|
ADDFEATURE("pop3p");
|
||||||
|
#endif
|
||||||
|
#ifdef WITH_SMTPP
|
||||||
|
ADDFEATURE("smtpp");
|
||||||
|
#endif
|
||||||
|
#ifdef WITH_IMAPP
|
||||||
|
ADDFEATURE("imapp");
|
||||||
|
#endif
|
||||||
|
#ifndef NOPLUGINS
|
||||||
|
ADDFEATURE("plugins");
|
||||||
|
#endif
|
||||||
|
#undef ADDFEATURE
|
||||||
|
return featsbuf;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/* A comma separated list of options, each NAME or NAME=VALUE; a name alone
|
/* A comma separated list of options, each NAME or NAME=VALUE; a name alone
|
||||||
stands for 1, or for TCP_MAXSEG for the value of maxseg. Options are added
|
stands for 1, or for TCP_MAXSEG for the value of maxseg. Options are added
|
||||||
to what is already set, so a default is changed only by naming it, and
|
to what is already set, so a default is changed only by naming it, and
|
||||||
@@ -364,6 +429,7 @@ static int srvprepare(struct srvstart *s, int argc, char **argv){
|
|||||||
" association: 1 - log, 2 - authorize, 3 - both (default), 0 (same as -U) -\n"
|
" association: 1 - log, 2 - authorize, 3 - both (default), 0 (same as -U) -\n"
|
||||||
" neither. The first destination is always authorized and logged\n"
|
" neither. The first destination is always authorized and logged\n"
|
||||||
#endif
|
#endif
|
||||||
|
" -B split the TLS ClientHello passed through tlspr at the SNI (DPI bypass)\n"
|
||||||
"-g(GRACE_TRAFF,GRACE_NUM,GRACE_DELAY) - delay GRACE_DELAY milliseconds before polling if average polling size below GRACE_TRAFF bytes and GRACE_NUM read operations in single directions are detected within 1 second to minimize polling\n"
|
"-g(GRACE_TRAFF,GRACE_NUM,GRACE_DELAY) - delay GRACE_DELAY milliseconds before polling if average polling size below GRACE_TRAFF bytes and GRACE_NUM read operations in single directions are detected within 1 second to minimize polling\n"
|
||||||
" -fFORMAT logging format (see documentation)\n"
|
" -fFORMAT logging format (see documentation)\n"
|
||||||
" -l log to stderr\n"
|
" -l log to stderr\n"
|
||||||
@@ -631,6 +697,13 @@ static int srvprepare(struct srvstart *s, int argc, char **argv){
|
|||||||
case 'U':
|
case 'U':
|
||||||
srv->udpauth = *(argv[i]+2)? atoi(argv[i]+2) : 0;
|
srv->udpauth = *(argv[i]+2)? atoi(argv[i]+2) : 0;
|
||||||
break;
|
break;
|
||||||
|
case 'B':
|
||||||
|
/* the TLS ClientHello split at the SNI (tlspr), which -s is
|
||||||
|
where -s is not splice; s_option means something else
|
||||||
|
for these */
|
||||||
|
if(!s->isudp && srv->service != S_ADMIN && srv->service != S_HTTPSRV)
|
||||||
|
srv->s_option = 1 + atoi(argv[i]+2);
|
||||||
|
break;
|
||||||
case 's':
|
case 's':
|
||||||
#ifdef WITHSPLICE
|
#ifdef WITHSPLICE
|
||||||
/* admin is an httpsrv, where -s is the limited mode */
|
/* admin is an httpsrv, where -s is the limited mode */
|
||||||
@@ -864,6 +937,8 @@ static int cblisten(struct srvstart *s){
|
|||||||
return -6;
|
return -6;
|
||||||
}
|
}
|
||||||
setopts(srv->cbsock, &srv->cbssockopts);
|
setopts(srv->cbsock, &srv->cbssockopts);
|
||||||
|
/* the clients of the service all wait for it: one accepts what comes */
|
||||||
|
nonblock(srv->cbsock);
|
||||||
|
|
||||||
if(srv->so._bind(srv->so.state, srv->cbsock, (struct sockaddr*)&cbsa, SASIZE(&cbsa))==-1) {
|
if(srv->so._bind(srv->so.state, srv->cbsock, (struct sockaddr*)&cbsa, SASIZE(&cbsa))==-1) {
|
||||||
dolog(defparam, (unsigned char *)"Failed to bind connect back socket");
|
dolog(defparam, (unsigned char *)"Failed to bind connect back socket");
|
||||||
|
|||||||
+7
-4
@@ -167,6 +167,7 @@ uint32_t udpresolve(int af, unsigned char * name, unsigned char * value, uint32_
|
|||||||
k += 4;
|
k += 4;
|
||||||
if(na > 255) na = 255; /* somebody is very evil */
|
if(na > 255) na = 255; /* somebody is very evil */
|
||||||
for (j = 0; j < na; j++) { /* now there should be answers */
|
for (j = 0; j < na; j++) { /* now there should be answers */
|
||||||
|
if(k >= len) break;
|
||||||
while(buf[k] < 192 && buf[k] !=0 && (k+buf[k]+14) < len) k+= (buf[k] + 1);
|
while(buf[k] < 192 && buf[k] !=0 && (k+buf[k]+14) < len) k+= (buf[k] + 1);
|
||||||
if(!buf[k]) k--;
|
if(!buf[k]) k--;
|
||||||
if((k+(af == AF_INET6?28:16)) > len) {
|
if((k+(af == AF_INET6?28:16)) > len) {
|
||||||
@@ -195,12 +196,14 @@ uint32_t udpresolve(int af, unsigned char * name, unsigned char * value, uint32_
|
|||||||
k+= (12 + flen);
|
k+= (12 + flen);
|
||||||
continue; /* we need A PTR */
|
continue; /* we need A PTR */
|
||||||
}
|
}
|
||||||
for (s2 = buf + k + 12; s2 < (buf + k + 12 + len) && *s2; ){
|
s1 = buf + k + 12 + flen; /* the end of this record's data, inside the answer */
|
||||||
s1 = s2 + ((unsigned)*s2) + 1;
|
for (s2 = buf + k + 12; s2 < s1 && *s2 && *s2 < 64; ){
|
||||||
|
unsigned char *next = s2 + ((unsigned)*s2) + 1;
|
||||||
*s2 = '.';
|
*s2 = '.';
|
||||||
s2 = s1;
|
s2 = next;
|
||||||
}
|
}
|
||||||
*s2 = 0;
|
if(s2 >= s1 || *s2 || s2 == buf + k + 12)
|
||||||
|
break; /* the name runs past its data, is compressed or empty */
|
||||||
if(param->username)free(param->username);
|
if(param->username)free(param->username);
|
||||||
param->username = (unsigned char *)strdup ((char *)buf + k + 13);
|
param->username = (unsigned char *)strdup ((char *)buf + k + 13);
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
#ifndef WITHMAIN
|
||||||
{
|
{
|
||||||
int action, reqbufsize, reqsize;
|
int action, reqbufsize, reqsize;
|
||||||
|
|||||||
+6
-1
@@ -119,7 +119,10 @@ void * sockschild(struct clientparam* param) {
|
|||||||
}
|
}
|
||||||
res = socks5_setaddr(param->srv->family, c, buf, ¶m->req);
|
res = socks5_setaddr(param->srv->family, c, buf, ¶m->req);
|
||||||
if(res == 1) {RETURN(997);}
|
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;
|
param->sinsr = param->req;
|
||||||
myinet_ntop(*SAFAMILY(¶m->sinsr), SAADDR(¶m->sinsr), (char *)buf, 64);
|
myinet_ntop(*SAFAMILY(¶m->sinsr), SAADDR(¶m->sinsr), (char *)buf, 64);
|
||||||
break;
|
break;
|
||||||
@@ -137,6 +140,7 @@ void * sockschild(struct clientparam* param) {
|
|||||||
default:
|
default:
|
||||||
RETURN(997);
|
RETURN(997);
|
||||||
}
|
}
|
||||||
|
if(badhostname((char *)buf)) {RETURN(21);}
|
||||||
if(param->hostname)free(param->hostname);
|
if(param->hostname)free(param->hostname);
|
||||||
param->hostname = (unsigned char *)strdup((char *)buf);
|
param->hostname = (unsigned char *)strdup((char *)buf);
|
||||||
if(!param->hostname){RETURN(21);}
|
if(!param->hostname){RETURN(21);}
|
||||||
@@ -159,6 +163,7 @@ void * sockschild(struct clientparam* param) {
|
|||||||
param->service = S_SOCKS45;
|
param->service = S_SOCKS45;
|
||||||
if(sockgetlinebuf(param, CLIENT, buf, BUFSIZE - 1, 0, conf.timeouts[STRING_S]) < 0) {RETURN(441);}
|
if(sockgetlinebuf(param, CLIENT, buf, BUFSIZE - 1, 0, conf.timeouts[STRING_S]) < 0) {RETURN(441);}
|
||||||
buf[127] = 0;
|
buf[127] = 0;
|
||||||
|
if(badhostname((char *)buf)) {RETURN(21);}
|
||||||
if(param->hostname)free(param->hostname);
|
if(param->hostname)free(param->hostname);
|
||||||
param->hostname = (unsigned char *)strdup((char *)buf);
|
param->hostname = (unsigned char *)strdup((char *)buf);
|
||||||
if(!param->hostname){RETURN(21);}
|
if(!param->hostname){RETURN(21);}
|
||||||
|
|||||||
@@ -74,6 +74,9 @@ static int client_mode = 0;
|
|||||||
struct SSLsock {
|
struct SSLsock {
|
||||||
SOCKET s;
|
SOCKET s;
|
||||||
SSL_CONN conn;
|
SSL_CONN conn;
|
||||||
|
/* what a read and a write which could not be done wait for, POLLIN
|
||||||
|
or POLLOUT, 0 once one is: TLS may have to write to read */
|
||||||
|
short rwant, wwant;
|
||||||
};
|
};
|
||||||
|
|
||||||
struct SSLstate {
|
struct SSLstate {
|
||||||
@@ -102,10 +105,12 @@ static void addSSL(
|
|||||||
if (cli_s != INVALID_SOCKET){
|
if (cli_s != INVALID_SOCKET){
|
||||||
SOSTATE->cli.s = cli_s;
|
SOSTATE->cli.s = cli_s;
|
||||||
SOSTATE->cli.conn = cli_conn;
|
SOSTATE->cli.conn = cli_conn;
|
||||||
|
SOSTATE->cli.rwant = SOSTATE->cli.wwant = 0;
|
||||||
}
|
}
|
||||||
if (srv_s != INVALID_SOCKET){
|
if (srv_s != INVALID_SOCKET){
|
||||||
SOSTATE->srv.s = srv_s;
|
SOSTATE->srv.s = srv_s;
|
||||||
SOSTATE->srv.conn = srv_conn;
|
SOSTATE->srv.conn = srv_conn;
|
||||||
|
SOSTATE->srv.rwant = SOSTATE->srv.wwant = 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -136,12 +141,14 @@ static ssize_t ssl_send(void *state, SOCKET s, const void *msg, size_t len, int
|
|||||||
int res, err;
|
int res, err;
|
||||||
if((res = ssl_write(sslq->conn, (void *)msg, len)) <= 0){
|
if((res = ssl_write(sslq->conn, (void *)msg, len)) <= 0){
|
||||||
err = SSL_get_error((SSL *)((ssl_conn*)sslq->conn)->ssl, res);
|
err = SSL_get_error((SSL *)((ssl_conn*)sslq->conn)->ssl, res);
|
||||||
if (err == SSL_ERROR_WANT_WRITE){
|
if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ){
|
||||||
|
sslq->wwant = (err == SSL_ERROR_WANT_READ)? POLLIN : POLLOUT;
|
||||||
seterrno3(EAGAIN);
|
seterrno3(EAGAIN);
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
else seterrno3(err);
|
else seterrno3(err);
|
||||||
}
|
}
|
||||||
|
else sslq->wwant = 0;
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -158,14 +165,16 @@ static ssize_t ssl_sendto(void *state, SOCKET s, const void *msg, size_t len, in
|
|||||||
|
|
||||||
if ((sslq = searchSSL(state, s))){
|
if ((sslq = searchSSL(state, s))){
|
||||||
int res, err;
|
int res, err;
|
||||||
if((res = ssl_write(sslq->conn, (void *)msg, len)) <= 0) {
|
if((res = ssl_write(sslq->conn, (void *)msg, len)) <= 0){
|
||||||
err = SSL_get_error((SSL *)((ssl_conn*)sslq->conn)->ssl, res);
|
err = SSL_get_error((SSL *)((ssl_conn*)sslq->conn)->ssl, res);
|
||||||
if (err == SSL_ERROR_WANT_WRITE){
|
if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ){
|
||||||
|
sslq->wwant = (err == SSL_ERROR_WANT_READ)? POLLIN : POLLOUT;
|
||||||
seterrno3(EAGAIN);
|
seterrno3(EAGAIN);
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
else seterrno3(err);
|
else seterrno3(err);
|
||||||
}
|
}
|
||||||
|
else sslq->wwant = 0;
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -183,12 +192,14 @@ static ssize_t ssl_recvfrom(void *state, SOCKET s, void *msg, size_t len, int f
|
|||||||
int res, err;
|
int res, err;
|
||||||
if((res = ssl_read(sslq->conn, (void *)msg, len)) <= 0) {
|
if((res = ssl_read(sslq->conn, (void *)msg, len)) <= 0) {
|
||||||
err = SSL_get_error((SSL *)((ssl_conn*)sslq->conn)->ssl, res);
|
err = SSL_get_error((SSL *)((ssl_conn*)sslq->conn)->ssl, res);
|
||||||
if (err == SSL_ERROR_WANT_READ) {
|
if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
|
||||||
|
sslq->rwant = (err == SSL_ERROR_WANT_WRITE)? POLLOUT : POLLIN;
|
||||||
seterrno3(EAGAIN);
|
seterrno3(EAGAIN);
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
else seterrno3(err);
|
else seterrno3(err);
|
||||||
}
|
}
|
||||||
|
else sslq->rwant = 0;
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
return sso._recvfrom(sso.state, s, msg, len, flags, from, fromlen);
|
return sso._recvfrom(sso.state, s, msg, len, flags, from, fromlen);
|
||||||
@@ -205,12 +216,14 @@ static ssize_t ssl_recv(void *state, SOCKET s, void *msg, size_t len, int flags)
|
|||||||
int res, err;
|
int res, err;
|
||||||
if((res = ssl_read(sslq->conn, (void *)msg, len)) <= 0) {
|
if((res = ssl_read(sslq->conn, (void *)msg, len)) <= 0) {
|
||||||
err = SSL_get_error((SSL *)((ssl_conn*)sslq->conn)->ssl, res);
|
err = SSL_get_error((SSL *)((ssl_conn*)sslq->conn)->ssl, res);
|
||||||
if (err == SSL_ERROR_WANT_READ) {
|
if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
|
||||||
|
sslq->rwant = (err == SSL_ERROR_WANT_WRITE)? POLLOUT : POLLIN;
|
||||||
seterrno3(EAGAIN);
|
seterrno3(EAGAIN);
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
else seterrno3(err);
|
else seterrno3(err);
|
||||||
}
|
}
|
||||||
|
else sslq->rwant = 0;
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -235,6 +248,8 @@ static int ssl_poll(void *state, struct pollfd *fds, nfds_t nfds, int timeout){
|
|||||||
struct SSLsock *sslq = NULL;
|
struct SSLsock *sslq = NULL;
|
||||||
unsigned int i;
|
unsigned int i;
|
||||||
int ret = 0;
|
int ret = 0;
|
||||||
|
short own[64], *events = own, ev;
|
||||||
|
|
||||||
for(i = 0; i < nfds; i++){
|
for(i = 0; i < nfds; i++){
|
||||||
if((fds[i].events & POLLIN) && (sslq = searchSSL(state, fds[i].fd)) && ssl_pending(sslq->conn)){
|
if((fds[i].events & POLLIN) && (sslq = searchSSL(state, fds[i].fd)) && ssl_pending(sslq->conn)){
|
||||||
fds[i].revents = POLLIN;
|
fds[i].revents = POLLIN;
|
||||||
@@ -243,8 +258,29 @@ static int ssl_poll(void *state, struct pollfd *fds, nfds_t nfds, int timeout){
|
|||||||
else fds[i].revents = 0;
|
else fds[i].revents = 0;
|
||||||
}
|
}
|
||||||
if(ret) return ret;
|
if(ret) return ret;
|
||||||
|
for(i = 0; i < nfds; i++) if((sslq = searchSSL(state, fds[i].fd)) && (sslq->rwant || sslq->wwant)) break;
|
||||||
|
if(i == nfds) return sso._poll(state, fds, nfds, timeout);
|
||||||
|
|
||||||
|
/* A read or a write TLS could not do waits for what TLS needs, a read
|
||||||
|
for the socket to be writable: whatever that gets is the caller's
|
||||||
|
chance to try again, revents what it asked for, and its events are
|
||||||
|
given back as they were. */
|
||||||
|
if(nfds > sizeof(own)/sizeof(own[0]) && !(events = malloc(nfds * sizeof(*events)))) return -1;
|
||||||
|
for(i = 0; i < nfds; i++){
|
||||||
|
events[i] = fds[i].events;
|
||||||
|
if(!(sslq = searchSSL(state, fds[i].fd))) continue;
|
||||||
|
ev = fds[i].events & ~(POLLIN|POLLOUT);
|
||||||
|
if(fds[i].events & POLLIN) ev |= sslq->rwant? sslq->rwant : POLLIN;
|
||||||
|
if(fds[i].events & POLLOUT) ev |= sslq->wwant? sslq->wwant : POLLOUT;
|
||||||
|
fds[i].events = ev;
|
||||||
|
}
|
||||||
ret = sso._poll(state, fds, nfds, timeout);
|
ret = sso._poll(state, fds, nfds, timeout);
|
||||||
|
for(i = 0; i < nfds; i++){
|
||||||
|
if(ret > 0 && fds[i].events != events[i] && (fds[i].revents & ~(POLLERR|POLLHUP|POLLNVAL)))
|
||||||
|
fds[i].revents = events[i] | (fds[i].revents & (POLLERR|POLLHUP|POLLNVAL));
|
||||||
|
fds[i].events = events[i];
|
||||||
|
}
|
||||||
|
if(events != own) free(events);
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -224,6 +224,7 @@ int parsehello(int type, unsigned char *hello, unsigned len, char *sni, int * sn
|
|||||||
else if(type == 2){
|
else if(type == 2){
|
||||||
offset += 3;
|
offset += 3;
|
||||||
}
|
}
|
||||||
|
if((offset + 2) > len) return -6;
|
||||||
elen = size16(hello+offset);
|
elen = size16(hello+offset);
|
||||||
offset += 2;
|
offset += 2;
|
||||||
if(elen+offset != len) return -9;
|
if(elen+offset != len) return -9;
|
||||||
|
|||||||
+8
-4
@@ -162,8 +162,10 @@ static void udpreset(struct clientparam *param)
|
|||||||
/*
|
/*
|
||||||
* Authorize param->req and (re)build the server side of the association:
|
* 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.
|
* 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
|
* Returns the authorization result. param->remsock is INVALID_SOCKET when
|
||||||
* socket can not be created, in this case the association can not continue.
|
* 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)
|
static int udpreconnect(struct clientparam *param)
|
||||||
{
|
{
|
||||||
@@ -189,9 +191,10 @@ static int udpreconnect(struct clientparam *param)
|
|||||||
param->remsock = INVALID_SOCKET;
|
param->remsock = INVALID_SOCKET;
|
||||||
}
|
}
|
||||||
udpreset(param);
|
udpreset(param);
|
||||||
|
return res;
|
||||||
}
|
}
|
||||||
if (udpbind(param)) return res? res : 11;
|
if (udpbind(param)) return 11;
|
||||||
return res;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
int udpsockmap(struct clientparam *param, int timeo)
|
int udpsockmap(struct clientparam *param, int timeo)
|
||||||
@@ -281,6 +284,7 @@ int udpsockmap(struct clientparam *param, int timeo)
|
|||||||
if (len < 7 + sz) return 485;
|
if (len < 7 + sz) return 485;
|
||||||
memcpy(dstnamebuf, base + 5, sz);
|
memcpy(dstnamebuf, base + 5, sz);
|
||||||
dstnamebuf[sz] = 0;
|
dstnamebuf[sz] = 0;
|
||||||
|
if (badhostname(dstnamebuf)) continue;
|
||||||
dstname = dstnamebuf;
|
dstname = dstnamebuf;
|
||||||
i = 5 + sz;
|
i = 5 + sz;
|
||||||
if (!getip46(param->srv->family, (unsigned char *)dstnamebuf,
|
if (!getip46(param->srv->family, (unsigned char *)dstnamebuf,
|
||||||
|
|||||||
+4
-4
@@ -1,14 +1,14 @@
|
|||||||
#ifndef VERSION
|
#ifndef VERSION
|
||||||
#define VERSION "3proxy-1.0.2"
|
#define VERSION "3proxy-1.0.4"
|
||||||
#endif
|
#endif
|
||||||
#ifndef BUILDDATE
|
#ifndef BUILDDATE
|
||||||
#define BUILDDATE "261024112140"
|
#define BUILDDATE "261121090854"
|
||||||
#endif
|
#endif
|
||||||
#define MAJOR3PROXY 1
|
#define MAJOR3PROXY 1
|
||||||
#define SUBMAJOR3PROXY 0
|
#define SUBMAJOR3PROXY 0
|
||||||
#define MINOR3PROXY 2
|
#define MINOR3PROXY 4
|
||||||
#define SUBMINOR3PROXY 0
|
#define SUBMINOR3PROXY 0
|
||||||
#define RELEASE3PROXY "3proxy-1.0.2(" BUILDDATE ")\0"
|
#define RELEASE3PROXY "3proxy-1.0.4(" BUILDDATE ")\0"
|
||||||
#ifndef YEAR3PROXY
|
#ifndef YEAR3PROXY
|
||||||
#define YEAR3PROXY "2026"
|
#define YEAR3PROXY "2026"
|
||||||
#endif
|
#endif
|
||||||
@@ -13,6 +13,14 @@ skips itself when that is missing or the build has no TLS support. With no
|
|||||||
`--bin` it looks in `bin/`, then `build/bin/`, then the per-configuration
|
`--bin` it looks in `bin/`, then `build/bin/`, then the per-configuration
|
||||||
directories a multi-configuration CMake generator uses.
|
directories a multi-configuration CMake generator uses.
|
||||||
|
|
||||||
|
The binary reports what it was built with in `3proxy --help` (a `built
|
||||||
|
with:` list), and the runner reads that before the first case: a case names
|
||||||
|
the features it needs with `if not t.skip_unless("ssl"): return`, and
|
||||||
|
skips on a build without them instead of failing. A binary too old to
|
||||||
|
report its features skips every case that needs one, and the cases with no
|
||||||
|
feature needs still run; some cases also probe at runtime, as a build can
|
||||||
|
leave a feature compiled in but unusable.
|
||||||
|
|
||||||
The proxy under test is also the origin server the tests talk to: the `http`
|
The proxy under test is also the origin server the tests talk to: the `http`
|
||||||
command's `echo` operation reports back how a request arrived - method, path,
|
command's `echo` operation reports back how a request arrived - method, path,
|
||||||
query, host, and the source port it came from - and `data` generates a body
|
query, host, and the source port it came from - and `data` generates a body
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import time
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
adm = t.free_port()
|
adm = t.free_port()
|
||||||
lim = t.free_port()
|
lim = t.free_port()
|
||||||
server = t.start("admin", f"""
|
server = t.start("admin", f"""
|
||||||
|
|||||||
+3
-1
@@ -7,7 +7,9 @@ handshake and the service supplies the port.
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
certs = t.certs()
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
|
certs = t.certs() if t.has("ssl") else None
|
||||||
plain = t.free_port()
|
plain = t.free_port()
|
||||||
port = t.free_port()
|
port = t.free_port()
|
||||||
secure = t.free_port() if certs else None
|
secure = t.free_port() if certs else None
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
"""The FTP proxy logging in to its server: whatever the server answers the
|
||||||
|
login with reaches the client, which waits for the answer to its PASS."""
|
||||||
|
|
||||||
|
import socket
|
||||||
|
import threading
|
||||||
|
|
||||||
|
# what the server answers USER with, and PASS if it asks for one
|
||||||
|
LOGINS = {
|
||||||
|
"230 to USER": ([b"230 Anonymous user logged in"], None),
|
||||||
|
"multiline 230 to USER": ([b"230-Welcome", b"230-to the server", b"230 Login successful."], None),
|
||||||
|
"331 to USER, 230 to PASS": ([b"331 Please specify the password."], [b"230 Login successful."]),
|
||||||
|
"530 to USER": ([b"530 Not allowed here"], None),
|
||||||
|
"331 to USER, 530 to PASS": ([b"331 Please specify the password."], [b"530 Login incorrect."]),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def ftp_server(listener, user, password):
|
||||||
|
"""Greets, answers the login as told, then NOOP and QUIT."""
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
c, _ = listener.accept()
|
||||||
|
except OSError:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
f = c.makefile("rb")
|
||||||
|
c.sendall(b"220 Fake FTP\r\n")
|
||||||
|
if not f.readline().upper().startswith(b"USER "):
|
||||||
|
continue
|
||||||
|
c.sendall(b"".join(line + b"\r\n" for line in user))
|
||||||
|
if password is not None:
|
||||||
|
if not f.readline().upper().startswith(b"PASS "):
|
||||||
|
continue
|
||||||
|
c.sendall(b"".join(line + b"\r\n" for line in password))
|
||||||
|
for line in f:
|
||||||
|
if line.upper().startswith(b"NOOP"):
|
||||||
|
c.sendall(b"200 NOOP ok\r\n")
|
||||||
|
elif line.upper().startswith(b"QUIT"):
|
||||||
|
c.sendall(b"221 Bye\r\n")
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
c.sendall(b"502 Not implemented\r\n")
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
c.close()
|
||||||
|
|
||||||
|
|
||||||
|
def reply(f):
|
||||||
|
"""The last line of a reply, multiline or not; empty at the end or on a
|
||||||
|
time out."""
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
line = f.readline()
|
||||||
|
except OSError:
|
||||||
|
return b""
|
||||||
|
if not line:
|
||||||
|
return b""
|
||||||
|
if len(line) < 4 or line[3:4] != b"-":
|
||||||
|
return line.rstrip()
|
||||||
|
|
||||||
|
|
||||||
|
def run(t):
|
||||||
|
if not t.skip_unless("ftppr"):
|
||||||
|
return
|
||||||
|
servers = {}
|
||||||
|
for name, (user, password) in LOGINS.items():
|
||||||
|
listener = socket.socket()
|
||||||
|
listener.bind(("127.0.0.1", 0))
|
||||||
|
listener.listen(5)
|
||||||
|
threading.Thread(target=ftp_server, args=(listener, user, password), daemon=True).start()
|
||||||
|
servers[name] = listener
|
||||||
|
|
||||||
|
port = t.free_port()
|
||||||
|
t.start("ftppr", f"""
|
||||||
|
log
|
||||||
|
auth none
|
||||||
|
ftppr -p{port}
|
||||||
|
""", ports=[port])
|
||||||
|
|
||||||
|
# without WITH_FTP the service closes the connection at once
|
||||||
|
s = socket.create_connection(("127.0.0.1", port), timeout=5)
|
||||||
|
built = reply(s.makefile("rb"))
|
||||||
|
s.close()
|
||||||
|
if not built:
|
||||||
|
t.skip("the FTP proxy (not built in this configuration)")
|
||||||
|
for listener in servers.values():
|
||||||
|
listener.close()
|
||||||
|
t.stop_all()
|
||||||
|
return
|
||||||
|
|
||||||
|
for name, listener in servers.items():
|
||||||
|
s = socket.create_connection(("127.0.0.1", port), timeout=5)
|
||||||
|
f = s.makefile("rb")
|
||||||
|
reply(f)
|
||||||
|
s.sendall(b"USER anonymous@127.0.0.1:%d\r\n" % listener.getsockname()[1])
|
||||||
|
reply(f)
|
||||||
|
s.sendall(b"PASS test@example.com\r\n")
|
||||||
|
got = reply(f)
|
||||||
|
ok = LOGINS[name][1] if LOGINS[name][1] is not None else LOGINS[name][0]
|
||||||
|
t.eq(ok[-1][:3], got[:3], f"{name}: the client gets the server's answer")
|
||||||
|
if got.startswith(b"230"):
|
||||||
|
s.sendall(b"NOOP\r\n")
|
||||||
|
t.eq(b"200", reply(f)[:3], f"{name}: and the session goes on")
|
||||||
|
s.close()
|
||||||
|
|
||||||
|
for listener in servers.values():
|
||||||
|
listener.close()
|
||||||
|
t.stop_all()
|
||||||
@@ -1,7 +1,11 @@
|
|||||||
"""Authentication and access rules in front of the HTTP server."""
|
"""Authentication and access rules in front of the HTTP server."""
|
||||||
|
|
||||||
|
import base64
|
||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
srv = t.free_port()
|
srv = t.free_port()
|
||||||
openport = t.free_port()
|
openport = t.free_port()
|
||||||
t.start("httpsrv_auth", f"""
|
t.start("httpsrv_auth", f"""
|
||||||
@@ -47,3 +51,19 @@ def run(t):
|
|||||||
|
|
||||||
t.contains(t.http(url + "/echo", auth=("alice", "secret")), "path=/echo",
|
t.contains(t.http(url + "/echo", auth=("alice", "secret")), "path=/echo",
|
||||||
"an authenticated request is dispatched")
|
"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")
|
||||||
@@ -8,6 +8,8 @@ import os
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
root = os.path.join(t.tmpdir, "web")
|
root = os.path.join(t.tmpdir, "web")
|
||||||
os.makedirs(os.path.join(root, "picts", "set"), exist_ok=True)
|
os.makedirs(os.path.join(root, "picts", "set"), exist_ok=True)
|
||||||
with open(os.path.join(root, "a.html"), "w") as fp:
|
with open(os.path.join(root, "a.html"), "w") as fp:
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ import os
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
root = os.path.join(t.tmpdir, "ka")
|
root = os.path.join(t.tmpdir, "ka")
|
||||||
os.makedirs(root, exist_ok=True)
|
os.makedirs(root, exist_ok=True)
|
||||||
with open(os.path.join(root, "a.html"), "w") as fp:
|
with open(os.path.join(root, "a.html"), "w") as fp:
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import time
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
srv = t.free_port()
|
srv = t.free_port()
|
||||||
t.start("httpsrv_ops", f"""
|
t.start("httpsrv_ops", f"""
|
||||||
log
|
log
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ most of them away before they ever reached the server.
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
srv = t.free_port()
|
srv = t.free_port()
|
||||||
t.start("httpsrv_parsing", f"""
|
t.start("httpsrv_parsing", f"""
|
||||||
log
|
log
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ import os
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
root = os.path.join(t.tmpdir, "pp")
|
root = os.path.join(t.tmpdir, "pp")
|
||||||
os.makedirs(root, exist_ok=True)
|
os.makedirs(root, exist_ok=True)
|
||||||
with open(os.path.join(root, "a.html"), "w") as fp:
|
with open(os.path.join(root, "a.html"), "w") as fp:
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
srv = t.free_port()
|
srv = t.free_port()
|
||||||
srv2 = t.free_port()
|
srv2 = t.free_port()
|
||||||
t.start("httpsrv_rules", f"""
|
t.start("httpsrv_rules", f"""
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ nscache6: nscache holds the IPv4 side and nothing else.
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv", "ipv6"):
|
||||||
|
return
|
||||||
if not t.has_ipv6():
|
if not t.has_ipv6():
|
||||||
t.skip("IPv6 (this machine has no IPv6 loopback)")
|
t.skip("IPv6 (this machine has no IPv6 loopback)")
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ import time
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
# The origin runs in a process of its own, so the limit only applies to
|
# The origin runs in a process of its own, so the limit only applies to
|
||||||
# the mapper in front of it.
|
# the mapper in front of it.
|
||||||
origin = t.free_port()
|
origin = t.free_port()
|
||||||
|
|||||||
@@ -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.
|
case here needs at most one parent to fail before a working one is reached.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import socket
|
||||||
|
import struct
|
||||||
import time
|
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):
|
def served(server, needle, since=0):
|
||||||
"""How many log lines carrying needle a proxy wrote past offset since."""
|
"""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)
|
return sum(1 for line in server.output()[since:].splitlines() if needle in line)
|
||||||
@@ -30,6 +43,8 @@ def wait_served(server, needle, count, since=0, timeout=5.0):
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
srv = t.free_port()
|
srv = t.free_port()
|
||||||
good = t.free_port()
|
good = t.free_port()
|
||||||
spare = t.free_port()
|
spare = t.free_port()
|
||||||
@@ -150,6 +165,90 @@ def run(t):
|
|||||||
t.eq(1, wait_served(goodp, needle, 1, gmark),
|
t.eq(1, wait_served(goodp, needle, 1, gmark),
|
||||||
"through the parent it names")
|
"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 --------------------------------------
|
# --- what the parser still rejects --------------------------------------
|
||||||
out = t.run_config("failover_badweight", f"""
|
out = t.run_config("failover_badweight", f"""
|
||||||
auth iponly
|
auth iponly
|
||||||
|
|||||||
@@ -46,6 +46,8 @@ UNHONOURED = (1, 99)
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
srv = t.free_port()
|
srv = t.free_port()
|
||||||
prx = t.free_port()
|
prx = t.free_port()
|
||||||
sks = t.free_port()
|
sks = t.free_port()
|
||||||
|
|||||||
@@ -37,6 +37,8 @@ def wait_served(server, needle, count, since=0, timeout=5.0):
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
adm = t.free_port()
|
adm = t.free_port()
|
||||||
prx = t.free_port()
|
prx = t.free_port()
|
||||||
dummy = t.free_port()
|
dummy = t.free_port()
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ def _has_pcre(t):
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv", "pcre"):
|
||||||
|
return
|
||||||
if not _has_pcre(t):
|
if not _has_pcre(t):
|
||||||
t.skip("PCRE (this build has no PCRE support)")
|
t.skip("PCRE (this build has no PCRE support)")
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -26,6 +26,8 @@ def halfclose_origin(listener):
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
# --- tcppm ---------------------------------------------------------
|
# --- tcppm ---------------------------------------------------------
|
||||||
origin = t.free_port()
|
origin = t.free_port()
|
||||||
mapped = t.free_port()
|
mapped = t.free_port()
|
||||||
|
|||||||
@@ -4,8 +4,12 @@ Access rules accumulate until "flush", so each service section here starts
|
|||||||
from a clean list.
|
from a clean list.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import base64
|
||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
srv = t.free_port()
|
srv = t.free_port()
|
||||||
other = t.free_port()
|
other = t.free_port()
|
||||||
prx = t.free_port()
|
prx = t.free_port()
|
||||||
@@ -106,3 +110,18 @@ def run(t):
|
|||||||
t.eq(407, t.http(origin + "/echo", proxy=needs_auth,
|
t.eq(407, t.http(origin + "/echo", proxy=needs_auth,
|
||||||
proxy_auth=("alice", "wrong")).status,
|
proxy_auth=("alice", "wrong")).status,
|
||||||
"wrong proxy credentials are refused")
|
"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")
|
||||||
@@ -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")
|
||||||
@@ -1,7 +1,23 @@
|
|||||||
"""The SOCKS proxy, reaching the built-in server."""
|
"""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):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
srv = t.free_port()
|
srv = t.free_port()
|
||||||
sks = t.free_port()
|
sks = t.free_port()
|
||||||
sauth = t.free_port()
|
sauth = t.free_port()
|
||||||
@@ -94,3 +110,121 @@ def run(t):
|
|||||||
"wrong SOCKS5 credentials are refused")
|
"wrong SOCKS5 credentials are refused")
|
||||||
t.ne(None, t.socks_connect(guarded, "127.0.0.1", srv),
|
t.ne(None, t.socks_connect(guarded, "127.0.0.1", srv),
|
||||||
"SOCKS5 without credentials is refused")
|
"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()
|
||||||
@@ -11,6 +11,8 @@ def _no_tls(t, server):
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv", "ssl"):
|
||||||
|
return
|
||||||
certs = t.certs()
|
certs = t.certs()
|
||||||
if not certs:
|
if not certs:
|
||||||
t.skip("TLS (openssl is not available to generate certificates)")
|
t.skip("TLS (openssl is not available to generate certificates)")
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv", "ssl"):
|
||||||
|
return
|
||||||
certs = t.certs()
|
certs = t.certs()
|
||||||
if not certs:
|
if not certs:
|
||||||
t.skip("tlspr (openssl is not available to generate certificates)")
|
t.skip("tlspr (openssl is not available to generate certificates)")
|
||||||
|
|||||||
@@ -39,6 +39,8 @@ def _config(t, name, body):
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
# --- the command and its modes ------------------------------------
|
# --- the command and its modes ------------------------------------
|
||||||
# These need no redirection, so they run wherever the feature is built.
|
# These need no redirection, so they run wherever the feature is built.
|
||||||
out = _config(t, "transparent_probe", "log\ntransparent")
|
out = _config(t, "transparent_probe", "log\ntransparent")
|
||||||
|
|||||||
@@ -36,6 +36,8 @@ def unix_get(path, url, timeout=10):
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv", "unix"):
|
||||||
|
return
|
||||||
if not hasattr(socket, "AF_UNIX") or sys.platform.startswith("win"):
|
if not hasattr(socket, "AF_UNIX") or sys.platform.startswith("win"):
|
||||||
t.skip("Unix domain sockets (not on this platform)")
|
t.skip("Unix domain sockets (not on this platform)")
|
||||||
return
|
return
|
||||||
|
|||||||
+21
-1
@@ -122,10 +122,11 @@ class Failure(Exception):
|
|||||||
class Tester:
|
class Tester:
|
||||||
"""The API a case runs against: start servers, make requests, assert."""
|
"""The API a case runs against: start servers, make requests, assert."""
|
||||||
|
|
||||||
def __init__(self, binary, tmpdir, case):
|
def __init__(self, binary, tmpdir, case, features=None):
|
||||||
self.binary = binary
|
self.binary = binary
|
||||||
self.tmpdir = tmpdir
|
self.tmpdir = tmpdir
|
||||||
self.case = case
|
self.case = case
|
||||||
|
self.features = features if features is not None else frozenset()
|
||||||
self.servers = []
|
self.servers = []
|
||||||
self.checks = []
|
self.checks = []
|
||||||
self.timeout = 10
|
self.timeout = 10
|
||||||
@@ -135,6 +136,25 @@ class Tester:
|
|||||||
self.logs = []
|
self.logs = []
|
||||||
self.udp_servers = []
|
self.udp_servers = []
|
||||||
|
|
||||||
|
# ---- build features ----------------------------------------------
|
||||||
|
|
||||||
|
def has(self, *names):
|
||||||
|
"""Whether the binary reports every named feature."""
|
||||||
|
return all(name in self.features for name in names)
|
||||||
|
|
||||||
|
def skip_unless(self, *names):
|
||||||
|
"""Skip what needs a feature the binary was built without.
|
||||||
|
|
||||||
|
Returns False after recording the skip, so a case says
|
||||||
|
`if not t.skip_unless("ssl"): return` and keeps its checks out of
|
||||||
|
the failed count on a build that cannot pass them.
|
||||||
|
"""
|
||||||
|
missing = [name for name in names if name not in self.features]
|
||||||
|
if not missing:
|
||||||
|
return True
|
||||||
|
self.skip("built without: " + ", ".join(missing))
|
||||||
|
return False
|
||||||
|
|
||||||
# ---- servers -----------------------------------------------------
|
# ---- servers -----------------------------------------------------
|
||||||
|
|
||||||
def has_ipv6(self):
|
def has_ipv6(self):
|
||||||
|
|||||||
+34
-1
@@ -47,6 +47,37 @@ def load_case(path):
|
|||||||
return name, module
|
return name, module
|
||||||
|
|
||||||
|
|
||||||
|
def built_features(binary):
|
||||||
|
"""The features the binary reports in `3proxy --help`, as a set.
|
||||||
|
|
||||||
|
A binary too old to have the list, or one that cannot be run at all,
|
||||||
|
reports nothing: every case that needs a feature then skips, and the
|
||||||
|
ones that need none still run.
|
||||||
|
"""
|
||||||
|
import subprocess
|
||||||
|
try:
|
||||||
|
done = subprocess.run([binary, "--help"], stdout=subprocess.PIPE,
|
||||||
|
stderr=subprocess.STDOUT, timeout=15)
|
||||||
|
text = done.stdout.decode("utf-8", "replace")
|
||||||
|
except (OSError, subprocess.SubprocessError):
|
||||||
|
return frozenset()
|
||||||
|
features = set()
|
||||||
|
collecting = False
|
||||||
|
for line in text.splitlines():
|
||||||
|
stripped = line.strip()
|
||||||
|
if line.startswith("built with:"):
|
||||||
|
collecting = True
|
||||||
|
rest = stripped[len("built with:"):].strip()
|
||||||
|
if rest:
|
||||||
|
features.update(rest.split())
|
||||||
|
continue
|
||||||
|
if collecting:
|
||||||
|
if not line[:1].isspace() or not stripped:
|
||||||
|
break
|
||||||
|
features.update(stripped.split())
|
||||||
|
return frozenset(features)
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
parser = argparse.ArgumentParser()
|
parser = argparse.ArgumentParser()
|
||||||
parser.add_argument("pattern", nargs="?", default="",
|
parser.add_argument("pattern", nargs="?", default="",
|
||||||
@@ -75,7 +106,9 @@ def main():
|
|||||||
return 2
|
return 2
|
||||||
|
|
||||||
tmpdir = tempfile.mkdtemp(prefix="3proxy-tests.")
|
tmpdir = tempfile.mkdtemp(prefix="3proxy-tests.")
|
||||||
|
features = built_features(binary)
|
||||||
print(f"3proxy tests: {binary}")
|
print(f"3proxy tests: {binary}")
|
||||||
|
print(f"built with: {' '.join(sorted(features)) or '(nothing reported)'}")
|
||||||
print(f"working in: {tmpdir}\n")
|
print(f"working in: {tmpdir}\n")
|
||||||
|
|
||||||
passed = failed = skipped = 0
|
passed = failed = skipped = 0
|
||||||
@@ -85,7 +118,7 @@ def main():
|
|||||||
for path in paths:
|
for path in paths:
|
||||||
name, module = load_case(path)
|
name, module = load_case(path)
|
||||||
print(f" {name}")
|
print(f" {name}")
|
||||||
tester = Tester(binary, tmpdir, name)
|
tester = Tester(binary, tmpdir, name, features)
|
||||||
error = None
|
error = None
|
||||||
try:
|
try:
|
||||||
module.run(tester)
|
module.run(tester)
|
||||||
|
|||||||
Reference in new issue
Block a user